如何发送Java POST请求

时间:2018-03-31 22:51:49

标签: java post http-post

我完全迷失了如何用Java发送POST请求。我理解如何在Python中使用请求模块,但没有运气的Java。所以,我想知道是否有人可以通过登录如instagram.com这样的网页给我一个明确的例子。我感谢所有回复。提前谢谢。

3 个答案:

答案 0 :(得分:2)

您可以使用Spring Web RestTemplate:

new RestTemplate().postForObject(url, requestObject, responseType);

答案 1 :(得分:2)

如果您不想使用额外的库,可以尝试HttpURLConnection:

public static String doPost(String url, String postData) {
    PrintWriter out = null;
    BufferedReader in = null;
    String result = "";
    try {
        URL realUrl = new URL(url);
        // build connection
        URLConnection conn = realUrl.openConnection();
        // set request properties
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
        // enable output and input
        conn.setDoOutput(true);
        conn.setDoInput(true);
        out = new PrintWriter(conn.getOutputStream());
        // send POST DATA
        out.print(postData);
        out.flush();
        in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            result += "/n" + line;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    finally {
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return result;
}

答案 2 :(得分:1)

你可以使用OkHttp

https://github.com/square/okhttp

public static final MediaType JSON
    = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(JSON, json);
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  Response response = client.newCall(request).execute();
  return response.body().string();
}