java 调用http post请求传json过去
时间: 2024-12-24 22:36:11 浏览: 3
在Java中,通常会使用`HttpURLConnection`、`HttpClient`或第三方库如`Apache HttpClient`、`OkHttp`来进行HTTP POST请求并传递JSON数据。这里以常用的`HttpURLConnection`为例,展示如何发送POST请求并将JSON作为请求体:
```java
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
public JSONObject sendPostJsonRequest(String url, JSONObject json) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法为POST
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
// 将JSON转换为字节数组,并写入连接的输入流
OutputStream os = con.getOutputStream();
byte[] data = json.toString().getBytes("UTF-8");
os.write(data);
os.flush();
os.close();
// 获取响应状态码
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
String response = readResponse(con.getInputStream());
return new JSONObject(response); // 如果需要返回JSON对象,解析响应内容
} else {
throw new RuntimeException("Failed : HTTP error code : " + responseCode);
}
}
private String readResponse(InputStream in) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
response.append(line);
}
br.close();
return response.toString();
}
```
阅读全文