用java生成一段post调用接口的方法,要求请求和返回参数为json格式,并且请求中要包含header信息
时间: 2024-06-08 20:09:48 浏览: 90
可以使用Java中的HttpURLConnection类来实现这个功能。下面是一个示例代码:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class PostJsonWithHeader {
public static void main(String[] args) throws Exception {
String url = "http://example.com/api";
String jsonBody = "{\"name\":\"John Doe\",\"age\":30}";
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", "Bearer abc123");
String response = postJsonWithHeader(url, jsonBody, headers);
System.out.println(response);
}
public static String postJsonWithHeader(String url, String jsonBody, Map<String, String> headers) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// Set request method and headers
con.setRequestMethod("POST");
for (Map.Entry<String, String> entry : headers.entrySet()) {
con.setRequestProperty(entry.getKey(), entry.getValue());
}
// Send request
con.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(jsonBody);
wr.flush();
// Get response
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
}
```
在这个示例代码中,我们首先定义了要调用的API接口的URL、请求体中的JSON数据以及请求头信息。然后,我们调用了`postJsonWithHeader`方法,该方法接受这些参数并实现了POST请求。具体来说,它首先使用HttpURLConnection类打开连接,并设置请求方法和请求头。然后,它将JSON数据写入请求体,并发送请求。最后,它读取响应并返回响应的字符串表示。
阅读全文