java发送post请求发送json的工具类封装
时间: 2023-11-12 11:57:58 浏览: 72
可以将发送 POST 请求发送 JSON 数据的代码封装为一个工具类,方便在项目中复用。以下是一个简单的工具类示例:
```java
import java.io.*;
import java.net.*;
public class HttpUtils {
public static String sendPostJson(String url, String json) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(json);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
}
```
在工具类中,我们定义了一个静态方法 `sendPostJson`,它接受两个参数:要发送 POST 请求的 URL 和要发送的 JSON 数据。方法中的代码与之前示例中的代码相同,只不过我们将其封装在了一个方法中,并将响应内容作为返回值。使用时,只需要调用该方法即可:
```java
String url = "https://example.com/api/endpoint";
String json = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
String response = HttpUtils.sendPostJson(url, json);
System.out.println("Response : " + response);
```
请注意,这只是一个简单的示例,实际应用中可能需要更加完善的异常处理等。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)