java后台调用post请求,请求参数是json数据格式的请求体,代码如何实现?
时间: 2023-05-20 22:04:36 浏览: 103
可以使用 Java 的 HttpURLConnection 类来实现后台调用 post 请求,以下是一个示例代码:
```java
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.OutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class PostJsonRequest {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com/api");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
String jsonInputString = "{\"name\": \"John\", \"age\": 30}";
try(OutputStream os = conn.getOutputStream()) {
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
}
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
这个示例代码中,我们首先创建了一个 URL 对象,然后使用 HttpURLConnection 类来打开连接。我们设置了请求方法为 POST,请求头的 Content-Type 为 application/json,然后设置了请求体。最后,我们读取了服务器返回的响应内容。
阅读全文