使用java发post请求,携带请求头,并且以json的形式携带请求体
时间: 2023-09-08 11:04:22 浏览: 113
使用java请求json接口数据
### 回答1:
好的,下面是在 Java 中使用 HttpURLConnection 发送 HTTP POST 请求的示例代码,携带请求头和以 JSON 的形式携带请求体。
首先,需要导入必要的类:
```
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
```
然后,可以使用以下代码来发送 POST 请求:
```
// 请求地址
String url = "https://example.com/api/v1/create";
// 创建 URL 对象
URL obj = new URL(url);
// 打开连接
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法
con.setRequestMethod("POST");
// 设置请求头
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestProperty("Authorization", "Basic dXNlcm5hbWU6cGFzc3dvcmQ=");
// 设置是否向 HttpURLConnection 输出,因为这是发送 POST 请求,参数要放在请求体中,设置为 true
con.setDoOutput(true);
// 获取输出流
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
// 请求体
String json = "{\"key\":\"value\"}";
// 写入请求体
wr.writeBytes(json);
// 刷新、关闭
wr.flush();
wr.close();
// 获取响应状态
int responseCode = con.getResponseCode();
// 定义 BufferedReader 输入流来读取 URL 的响应
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 打印响应
System.out.println(response.toString());
```
希望这能帮到
### 回答2:
在Java中使用Post请求携带请求头并以JSON形式携带请求体,可以通过使用HttpURLConnection或Apache HttpClient库来实现。
1. 使用HttpURLConnection:
```
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class PostRequestExample {
public static void main(String[] args) {
try {
// 创建URL对象
URL url = new URL("http://www.example.com/api");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置请求方法为POST
conn.setRequestMethod("POST");
// 设置请求头信息
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "Bearer YOUR_ACCESS_TOKEN");
// 打开输出流
conn.setDoOutput(true);
// 创建请求体
String requestBody = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
// 发送请求体
OutputStream os = conn.getOutputStream();
os.write(requestBody.getBytes());
os.flush();
// 获取响应
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = br.readLine()) != null) {
response.append(line);
}
// 输出响应结果
System.out.println(response.toString());
// 关闭资源
br.close();
os.close();
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
2. 使用Apache HttpClient:
```
import org.apache.http.HttpResponse;
import org.apache.http.client.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 PostRequestExample {
public static void main(String[] args) {
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建HttpPost对象
HttpPost httpPost = new HttpPost("http://www.example.com/api");
// 设置请求头信息
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Authorization", "Bearer YOUR_ACCESS_TOKEN");
// 创建请求体
String requestBody = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
// 设置请求体
httpPost.setEntity(new StringEntity(requestBody));
// 发送请求
HttpResponse response = httpClient.execute(httpPost);
// 获取响应结果
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line;
StringBuilder result = new StringBuilder();
while ((line = br.readLine()) != null) {
result.append(line);
}
// 输出响应结果
System.out.println(result.toString());
// 关闭资源
br.close();
httpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
通过以上两种方法,我们可以在Java中使用Post请求携带请求头并以JSON形式携带请求体。注意替换示例代码中的URL、请求头和请求体内容。
### 回答3:
使用Java进行POST请求的方式有很多种,以下是一种实现方式:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class PostRequestExample {
public static void main(String[] args) {
try {
// 请求URL
URL url = new URL("http://example.com/api");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
// 设置请求头
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
// 设置请求体
String requestBody = "{\"key1\":\"value1\", \"key2\":\"value2\"}";
// 启用请求体
connection.setDoOutput(true);
OutputStream outputStream = connection.getOutputStream();
outputStream.write(requestBody.getBytes());
outputStream.flush();
outputStream.close();
// 获取响应
int responseCode = connection.getResponseCode();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = bufferedReader.readLine()) != null) {
response.append(inputLine);
}
bufferedReader.close();
// 输出响应结果
System.out.println("Response Code: " + responseCode);
System.out.println("Response Body: " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
上述代码示例使用HttpURLConnection类发送POST请求。首先指定了请求的URL,并将其打开为HttpURLConnection对象。然后设置POST请求的请求头,这里使用了Content-Type和Accept两个常见的请求头。接下来设置请求体,将请求参数以JSON字符串的形式写入请求体中。最后,发送请求并获取响应,获取响应的数据流并读取响应结果。
这样就可以使用Java发起带有请求头和以JSON形式携带请求体的POST请求了。请根据实际需要进行简单的修改和适配。
阅读全文