如何在Java中发送HTTP请求?

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

回答:

你可以使用java.net.HttpUrlConnection

示例(从此处开始),进行了改进。包括在链接腐烂的情况下:

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中发送HTTP请求? 的全部内容, 来源链接: utcz.com/qa/424231.html

回到顶部