java http post json对象请求
时间: 2024-12-22 11:23:22 浏览: 7
在Java中发送HTTP POST请求并携带JSON对象,通常会用到`HttpURLConnection`、`HttpClient`或者第三方库如`Apache HttpClient`或`OkHttp`。这里我会演示使用`HttpURLConnection`的基本示例:
```java
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
public JSONObject sendPostJson(String url, JSONObject json) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
// Write the JSON object to the request body
OutputStream os = con.getOutputStream();
byte[] jsonBytes = json.toString().getBytes("UTF-8");
os.write(jsonBytes);
os.flush();
os.close();
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
return readJson(con.getInputStream()); // assuming you have a method to parse JSON from InputStream
} else {
throw new RuntimeException("Failed : HTTP error code : " + responseCode);
}
}
private JSONObject readJson(InputStream is) throws Exception {
// Parse the JSON content here using a library like Jackson or Gson
// For example with Jackson:
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(is, JSONObject.class);
}
```
阅读全文