写一段Java的POST请求的多个报文调用https的工具类
时间: 2024-02-18 13:01:21 浏览: 77
好的,以下是一个简单的Java的POST请求调用https的工具类的示例代码,该代码支持多个请求报文的发送:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
public class HttpsUtil {
public static String sendPostRequests(String urlStr, List<String> requestDatas) {
String response = null;
try {
URL url = new URL(urlStr);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("charset", "utf-8");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
StringBuilder sb = new StringBuilder();
for (String requestData : requestDatas) {
sb.append(requestData).append("\n");
}
String data = sb.toString();
byte[] postData = data.getBytes(StandardCharsets.UTF_8);
conn.setRequestProperty("Content-Length", Integer.toString(postData.length));
conn.getOutputStream().write(postData);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer responseBuffer = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
responseBuffer.append(inputLine);
}
in.close();
response = responseBuffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
}
```
在上面的代码中,sendPostRequests方法接收两个参数:urlStr表示请求的地址,requestDatas表示请求的数据列表。该方法使用HttpsURLConnection对象发送POST请求,并将所有请求报文按照换行符拼接为一个字符串,然后将该字符串转换为字节数组并发送。最后,将响应结果读取为字符串并返回。
请注意,在实际使用中,您需要对代码进行修改以适应您的具体需求,例如更改请求头、请求参数、超时时间等。同时,您也需要根据接口文档要求,将请求数据按照指定格式进行拼接。
阅读全文