为HTTP POST请求设置请求体
1. 使用 HttpURLConnection
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpPostExample {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com/api");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置为POST请求并允许输出
connection.setRequestMethod("POST");
connection.setDoOutput(true);
// 设置请求体数据(例如表单格式)
String data = "key1=value1&key2=value2";
byte[] dataBytes = data.getBytes();
// 可选:设置Content-Type
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 写入请求体
OutputStream os = connection.getOutputStream();
os.write(dataBytes); os.flush();
os.close();
// 获取响应
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
} catch (Exception e) { e.printStackTrace();
} } }
2.使用 Apache HttpClient
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;
public class HttpClientExample {
public static void main(String[] args) {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost post = new HttpPost("http://example.com/api");
// 设置请求头
post.setHeader("Content-Type", "application/json");
// 设置请求体(JSON格式示例)
String jsonBody = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
post.setEntity(new StringEntity(jsonBody));
// 执行请求并获取响应 //
CloseableHttpResponse response = httpClient.execute(post);
// 处理响应...
} catch (Exception e)
{ e.printStackTrace();
} } }

浙公网安备 33010602011771号