java post请求带请求头
时间: 2023-10-18 14:29:04 浏览: 88
post请求
好的,下面是Java中带请求头的POST请求示例代码:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpPostWithHeaderExample {
public static void main(String[] args) throws Exception {
String url = "http://example.com/api";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法为POST
con.setRequestMethod("POST");
// 设置请求头
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Content-Type", "application/json");
// 设置POST请求体
String postBody = "{\"name\":\"John\", \"age\":30}";
con.setDoOutput(true);
con.getOutputStream().write(postBody.getBytes("UTF-8"));
// 发送POST请求
int responseCode = con.getResponseCode();
System.out.println("Sending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
// 读取响应内容
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 打印响应内容
System.out.println(response.toString());
}
}
```
在上面的代码中,我们首先创建一个URL对象,并打开一个HttpURLConnection连接。然后,我们设置请求方法为POST,并设置请求头。接下来,我们设置POST请求体,并发送POST请求。最后,我们读取响应内容并打印出来。
阅读全文