Java http工具类,post请求发送json参数
时间: 2024-02-05 14:04:07 浏览: 206
下面是一个Java的Http工具类,可以用于发送POST请求并且发送JSON参数:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class HttpUtils {
public static String post(String url, String 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");
con.setRequestProperty("Accept", "application/json");
// 开启输出流
con.setDoOutput(true);
// 发送请求
con.getOutputStream().write(json.getBytes(StandardCharsets.UTF_8));
// 获取响应状态码
int responseCode = con.getResponseCode();
// 读取响应内容
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
if (responseCode == HttpURLConnection.HTTP_OK) {
return response.toString();
} else {
throw new Exception("HTTP请求失败," + responseCode + " " + con.getResponseMessage());
}
}
}
```
使用方法:
```java
String url = "http://example.com/api";
String json = "{\"key\":\"value\"}";
String response = HttpUtils.post(url, json);
System.out.println(response);
```
阅读全文