java post 请求带请求头
时间: 2023-10-23 16:06:11 浏览: 78
java模拟post请求
4星 · 用户满意度95%
你可以使用 Java 的 HttpURLConnection 类发送带有请求头的 POST 请求,示例代码如下:
```
URL url = new URL("http://example.com/api");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "Bearer your_token_here");
conn.setDoOutput(true);
String requestBody = "{\"name\": \"John\", \"age\": 30}";
OutputStream os = conn.getOutputStream();
os.write(requestBody.getBytes());
os.flush();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String response = in.readLine();
System.out.println(response);
in.close();
} else {
System.out.println("POST request failed: " + conn.getResponseMessage());
}
```
在这个示例中,我们设置了 Content-Type 和 Authorization 两个请求头,并通过 setDoOutput(true) 方法允许发送请求体。最后,我们检查了响应状态码并读取了响应体。
阅读全文