帮我写一个Java的http请求工具类,包含Post和Get请求,并且支持传入header,也可以不传header等西悉尼
时间: 2023-06-01 13:05:02 浏览: 102
好的,我可以帮您解决。这里是一个示例Java的http请求工具类,它可以支持Post和Get请求,并且可以传入header或不传入header:
```
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpUtils {
public static String sendGet(String url, String headers) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求头
if (headers != null && headers.trim().length() > 0) {
String[] headerArray = headers.split("\n");
for (String header : headerArray) {
String[] parts = header.split(":");
con.setRequestProperty(parts[0].trim(), parts[1].trim());
}
}
// 发送GET请求
con.setRequestMethod("GET");
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();
}
// 发送Post请求
public static String sendPost(String url, String headers, String requestPayload) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求头
if (headers != null && headers.trim().length() > 0) {
String[] headerArray = headers.split("\n");
for (String header : headerArray) {
String[] parts = header.split(":");
con.setRequestProperty(parts[0].trim(), parts[1].trim());
}
}
// 发送POST请求
con.setRequestMethod("POST");
con.setDoOutput(true);
con.getOutputStream().write(requestPayload.getBytes("UTF-8"));
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();
}
}
```
使用示例:
```
// 发送GET请求
String url = "http://www.example.com/getData";
String headers = "Content-Type: application/json\nAuthorization: Bearer abcdefg";
String response = HttpUtils.sendGet(url, headers);
// 发送POST请求
String url = "http://www.example.com/postData";
String headers = "Content-Type: application/json\nAuthorization: Bearer abcdefg";
String requestPayload = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
String response = HttpUtils.sendPost(url, headers, requestPayload);
```
请注意,此示例仅供参考。在实际编写代码过程中,还需要考虑错误处理、性能优化等方面的问题。
阅读全文