java post请求带hader
时间: 2023-07-06 17:39:49 浏览: 77
好的,您可以使用以下Java代码发送带有Header的POST请求:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpUrlConnectionExample {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com/api");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
// 设置Header
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
// 设置请求体
String requestBody = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
con.setDoOutput(true);
con.getOutputStream().write(requestBody.getBytes("UTF-8"));
// 发送请求
int status = con.getResponseCode();
// 读取响应
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());
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
```
在上面的代码中,我们使用`con.setRequestProperty()`方法设置Header,然后使用`con.getOutputStream().write()`方法设置请求体。注意,我们必须设置`con.setDoOutput(true)`才能向请求体写入数据。
希望对您有帮助!
阅读全文