gpt4 book ai didi

java - 如何在 Java 中发送 HTTP 请求?

转载 作者:bug小助手 更新时间:2023-10-28 01:36:41 31 4
gpt4 key购买 nike

在 Java 中,如何编写 HTTP 请求消息并将其发送到 HTTP WebServer?

最佳答案

您可以使用 java.net.HttpUrlConnection .

示例 (from here),经过改进。包括在链接失效的情况下:

public static String executePost(String targetURL, String urlParameters) {
HttpURLConnection connection = null;

try {
//Create connection
URL url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");

connection.setRequestProperty("Content-Length",
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");

connection.setUseCaches(false);
connection.setDoOutput(true);

//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.close();

//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}

关于java - 如何在 Java 中发送 HTTP 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1359689/

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