gpt4 book ai didi

java - 在 Java 中使用 HttpURLConnection 进行 POST

转载 作者:塔克拉玛干 更新时间:2023-11-01 19:08:27 26 4
gpt4 key购买 nike

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

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

当我尝试这个时,我总是在调用 setRequestMethod 时得到一个“Connection Already Established” 异常,这非常有意义,因为我在设置请求之前明确调用了 openConnection类型。尽管阅读文档 openConnection 实际上并没有在理论上打开连接。

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

我猜这段代码在大多数情况下一定能正常工作,因为肯定有人测试过它,那么为什么这段代码对我不起作用?我应该如何编写这段代码?

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

最佳答案

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

这里的关键是理解 HttpURLConnection 类的复杂性。首次创建时,该类默认为“GET”请求方法,因此在此实例中无需更改任何内容。以下是相当不直观的,但是要将请求方法设置为“POST”您不应调用 setRequestMethod("POST"),而应调用 setDoOutput(true),它隐式地将请求方法设置为 post。完成后就可以开始了。

我相信,下面是 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();
}

关于java - 在 Java 中使用 HttpURLConnection 进行 POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26940410/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com