使用HttpURLConnection在Java中进行POST

时间:2014-11-14 23:17:04

标签: java http

我使用HttpURLConnection读了很多并尝试了很多与HTTP POSTS相关的内容,而我遇到的几乎所有内容都有类似的结构,从这3行开始:

  url = new URL(targetURL);
  connection = (HttpURLConnection)url.openConnection();
  connection.setRequestMethod("POST");

当我尝试这个时,我总是在调用 setRequestMethod 时得到一个" Connection已经建立" 例外,这非常有意义,因为我是在设置请求类型之前清楚地调用openConnection。虽然阅读文档openConnection实际上并没有在理论上打开连接。

有关此问题的几篇帖子,例如thisthis。我不明白为什么关于如何编写此代码的每条建议都按此顺序排列这3行。

我猜这个代码必须在大多数情况下都能正常工作,因为有人必须对其进行测试,那么为什么这段代码不适合我呢?我该怎么写这段代码?

我知道这些是我可以在那里使用的其他库,我只是想知道为什么这不起作用。

2 个答案:

答案 0 :(得分:1)

为什么问题中的可疑代码在整个互联网上都是重复的,这是我无法回答的问题。我也无法回答为什么它似乎适用于某些人而不是其他人。然而,我现在可以回答另一个问题,主要是感谢Luiggi指出的this link

这里的关键是理解HttpURLConnection类的复杂性。首次创建时,类默认为" GET"请求方法,因此在这个实例中不需要更改任何内容。以下内容相当不直观,但要将请求方法设置为" POST" 你不应该调用setRequestMethod(" POST"),而是setDoOutput(true)隐式设置要发布的请求方法。一旦你做完了,你就会好起来。

下面,我相信,post方法应该是什么样子。这是用于发布json,但显然可以针对任何其他内容类型进行更改。

public static String doPostSync(final String urlToRead, final String content) throws IOException {
    final String charset = "UTF-8";
    // Create the connection
    HttpURLConnection connection = (HttpURLConnection) new URL(urlToRead).openConnection();
    // setDoOutput(true) implicitly set's the request type to POST
    connection.setDoOutput(true);
    connection.setRequestProperty("Accept-Charset", charset);
    connection.setRequestProperty("Content-type", "application/json");

    // Write to the connection
    OutputStream output = connection.getOutputStream();
    output.write(content.getBytes(charset));
    output.close();

    // Check the error stream first, if this is null then there have been no issues with the request
    InputStream inputStream = connection.getErrorStream();
    if (inputStream == null)
        inputStream = connection.getInputStream();

    // Read everything from our stream
    BufferedReader responseReader = new BufferedReader(new InputStreamReader(inputStream, charset));

    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = responseReader.readLine()) != null) {
        response.append(inputLine);
    }
    responseReader.close();

    return response.toString();
}

答案 1 :(得分:0)

根据https://stackoverflow.com/a/3324964/436524,您需要致电connection.setDoOutput(true)以获得POST请求。

这使您的代码如下:

  url = new URL(targetURL);
  connection = (HttpURLConnection)url.openConnection();
  connection.setDoOutput(true);