简体   繁体   English

在Java中使用HttpURLConnection进行POST

[英]Using HttpURLConnection to POST in Java

I've read lots and tried lots relating to HTTP POSTS using HttpURLConnection and almost everything I come across has a similar structure which starts with these 3 lines: 我已经阅读了很多文章,并尝试使用HttpURLConnection进行许多与HTTP POST相关的尝试,并且我遇到的几乎所有内容都具有类似的结构,该结构以以下3行开头:

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

When I try this I always get a "Connection Already Established" exception when calling setRequestMethod , which makes perfect sense as I'm clearly calling openConnection before setting the request type. 尝试此操作时,在调用setRequestMethod时 ,总是会收到“已建立连接”异常,这很合情合理,因为在设置请求类型之前,我显然是在调用openConnection。 Although reading the docs openConnection doesn't actually open the connection in theory. 尽管阅读文档openConnection实际上并没有从理论上打开连接。

There are several posts about this problem on SO such as this and this . 关于SO的这个问题有好几篇文章,例如thisthis I don't understand however why every piece of advice about how to write this code has these 3 lines in this order. 但是我不明白为什么为什么有关如何编写此代码的每条建议都按顺序排列这三行。

I'm guessing this code must work in most instances as someone must have tested it, so why doesn't this code work for me? 我猜想这个代码必须在大多数情况下都可以工作,因为有人必须对其进行测试,所以为什么这个代码对我不起作用? How should I be writing this code? 我应该如何编写此代码?

I am aware these are other libraries I can use out there, I'm just wondering why this doesn't work. 我知道这些是我可以在其中使用的其他库,我只是想知道为什么这不起作用。

Why the suspect code in the question has been duplicated all over the internet is something I can't answer. 我无法回答为什么问题中的可疑代码已在整个Internet上重复的问题。 Nor can I answer why it seems to work for some people and not others. 我也无法回答为什么它似乎对某些人有用而对其他人无效。 I can however answer the other question now, mainly thanks to this link that Luiggi pointed me to. 但是,我现在可以回答另一个问题,这主要归功于Luiggi指向我的链接

The key here is understanding the intricacies of the HttpURLConnection class. 此处的关键是理解HttpURLConnection类的复杂性。 When first created the class defaults to a "GET" request method, so nothing needs to be changed in this instance. 首次创建时,该类默认为“ GET”请求方法,因此在此实例中无需进行任何更改。 The following is rather unintuitive, but to set the request method to "POST" you should not call setRequestMethod("POST") , but rather setDoOutput(true) which implicitly sets the request method to post. 以下内容非常不直观,但是要将请求方法设置为“ POST”, 您不应调用setRequestMethod(“ POST”) ,而应调用 setDoOutput(true),它会隐式将请求方法设置为post。 Once you've done that you're good to go. 完成后,您就可以开始了。

Below, I believe, is what a post method should look like. 我相信,下面是发布方法的外观。 This is for posting json, but can obviously be altered for any other content type. 这是用于发布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();
}

As per https://stackoverflow.com/a/3324964/436524 , you need to call connection.setDoOutput(true) for it to expect a POST request. 根据https://stackoverflow.com/a/3324964/436524 ,您需要调用connection.setDoOutput(true)才能期望POST请求。

This makes your code like this: 这使您的代码如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM