帮我使用java写一个http的工具类
时间: 2023-08-28 13:30:43 浏览: 76
java文件读写工具类分享
好的,以下是一个使用Java编写的HTTP工具类的示例,你可以根据自己的需求进行修改和完善:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
public class HttpUtil {
private String url;
public HttpUtil(String url) {
this.url = url;
}
public String get(Map<String, String> params, Map<String, String> headers) {
try {
String paramStr = generateParamString(params);
URL urlObj = new URL(this.url + paramStr);
HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
connection.setRequestMethod("GET");
setHeaders(connection, headers);
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
connection.disconnect();
return response.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public String post(String data, Map<String, String> headers) {
try {
URL urlObj = new URL(this.url);
HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
connection.setRequestMethod("POST");
setHeaders(connection, headers);
connection.setDoOutput(true);
connection.getOutputStream().write(data.getBytes());
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
connection.disconnect();
return response.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private void setHeaders(HttpURLConnection connection, Map<String, String> headers) {
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
}
private String generateParamString(Map<String, String> params) {
if (params == null) {
return "";
}
StringBuilder sb = new StringBuilder();
sb.append("?");
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(entry.getKey());
sb.append("=");
sb.append(entry.getValue());
sb.append("&");
}
return sb.toString();
}
}
```
这个类中包含了两个常用的HTTP请求方法:GET和POST,分别使用HttpURLConnection发送HTTP请求。其中,GET方法接受两个可选参数params和headers,用于指定请求参数和请求头。POST方法接受两个可选参数data和headers,用于指定POST请求参数和请求头。如果请求发生错误,则返回null。
阅读全文