一尘不染

Android GET和POST请求

java

谁能给我指出发送GET和POST请求的一种很好的实现方式。他们有很多方法可以做到这些,我正在寻找最佳的实现方式。其次,有一种通用的方法可以发送这两种方法,而不是使用两种不同的方法。毕竟,GET方法仅在查询字符串中具有参数,而POST方法使用这些参数的标头。

谢谢。


阅读 220

收藏
2020-12-03

共1个答案

一尘不染

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

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请求看起来会有些不同,但是很多代码是相同的。您不必担心用流进行输出或指定content-length或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();

  }
}
2020-12-03