以下是 Java 中进行 HTTP POST 请求的示例代码,包括使用 HttpURLConnection 和 HttpClient 两种方式,供您参考。
使用 HttpURLConnection 发送 POST 请求示例代码:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class HttpPostWithHttpURLConnection {
public static void main(String[] args) throws Exception {
String url = "http://httpbin.org/post";
String data = "name=value";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
wr.write(data.getBytes(StandardCharsets.UTF_8));
}
try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
String line;
StringBuilder response = new StringBuilder();
while ((line = in.readLine()) != null) {
response.append(line);
}
System.out.println(response.toString());
}
}
}
使用 HttpClient 发送 POST 请求示例代码:
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpPostWithHttpClient {
public static void main(String[] args) throws Exception {
String url = "http://httpbin.org/post";
String data = "name=value";
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
httpPost.setEntity(new StringEntity(data));
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpPost)) {
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
}
}
}
需要注意的是,在实际使用中,需要根据具体需求设置请求头、请求参数等信息。另外,这里的示例代码中使用了 try-with-resources 语句来自动关闭资源,建议在实际使用中也使用这种方式来规避资源泄漏的风险。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)