Android GET 和 POST 请求 [英] Android GET and POST Request

查看:34
本文介绍了Android GET 和 POST 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以向我指出发送 GET 和 POST 请求的方法的良好实现.他们有很多方法来做这些,我正在寻找最好的实现.其次,是否有一种通用的方式来发送这两种方法,而不是使用两种不同的方式.毕竟 GET 方法只在查询字符串中有参数,而 POST 方法使用参数的标题.

Can anyone point me to a good implementation of a way to send GET and POST Requests. They are alot of ways to do these, and i am looking for the best implementation. Secondly is there a generic way to send both these methods rather then using two different ways. After all the GET method merely has the params in the Query Strings, whereas the POST method uses the headers for the Params.

谢谢.

推荐答案

您可以使用 HttpURLConnection 类(在 java.net 中)发送 POST 或 GET HTTP 请求.它与可能想要发送 HTTP 请求的任何其他应用程序相同.发送 Http 请求的代码如下所示:

You can use the HttpURLConnection class (in java.net) to send a POST or GET HTTP request. It is the same as any other application that might want to send an HTTP request. The code to send an Http Request would look like this:

import java.net.*;
import java.io.*;
public class SendPostRequest {
  public static void main(String[] args) throws MalformedURLException, IOException {
    URL reqURL = new URL("http://www.stackoverflow.com/"); //the URL we will send the request to
    HttpURLConnection request = (HttpURLConnection) (reqUrl.openConnection());
    String post = "this will be the post data that you will send"
    request.setDoOutput(true);
    request.addRequestProperty("Content-Length", Integer.toString(post.length)); //add the content length of the post data
    request.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //add the content type of the request, most post data is of this type
    request.setMethod("POST");
    request.connect();
    OutputStreamWriter writer = new OutputStreamWriter(request.getOutputStream()); //we will write our request data here
    writer.write(post);
    writer.flush();
  }
}

GET 请求看起来有点不同,但大部分代码是相同的.您不必担心使用流进行输出或指定内容长度或内容类型:

A GET request will look a little bit different, but much of the code is the same. You don't have to worry about doing output with streams or specifying the content-length or content-type:

import java.net.*;
import java.io.*;

public class SendPostRequest {
  public static void main(String[] args) throws MalformedURLException, IOException {
    URL reqURL = new URL("http://www.stackoverflow.com/"); //the URL we will send the request to
    HttpURLConnection request = (HttpURLConnection) (reqUrl.openConnection());
    request.setMethod("GET");
    request.connect();

  }
}

这篇关于Android GET 和 POST 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆