帮我写一个Java的http请求工具类,包含Post和Get请求就行了
时间: 2023-06-01 17:04:59 浏览: 159
好的,我可以为您提供一个Java的http请求工具类。以下是示例代码:
```java
import java.net.*;
import java.io.*;
import java.util.*;
public class HttpUtil {
/**
* 发送HTTP GET请求
* @param url 请求的URL地址
* @return 响应结果
*/
public static String sendGetRequest(String url) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法为GET
con.setRequestMethod("GET");
// 发送请求
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
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();
} else {
throw new Exception("HTTP GET请求失败,错误代码:" + responseCode);
}
}
/**
* 发送HTTP POST请求
* @param url 请求的URL地址
* @param params 请求参数,以Map<String, String>的形式传入
* @return 响应结果
*/
public static String sendPostRequest(String url, Map<String, String> params) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法为POST
con.setRequestMethod("POST");
// 设置请求参数
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(getQueryString(params));
wr.flush();
wr.close();
// 发送请求
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
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();
} else {
throw new Exception("HTTP POST请求失败,错误代码:" + responseCode);
}
}
/**
* 将Map<String, String>类型的请求参数转换成字符串
*/
public static String getQueryString(Map<String, String> params) throws Exception {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first) {
first = false;
} else {
result.append("&");
}
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}
```
使用示例:
```java
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String[] args) {
try {
// 发送HTTP GET请求
String response1 = HttpUtil.sendGetRequest("http://www.baidu.com");
System.out.println("Response1: " + response1);
// 发送HTTP POST请求
Map<String, String> params = new HashMap<>();
params.put("username", "admin");
params.put("password", "admin");
String response2 = HttpUtil.sendPostRequest("http://example.com/login", params);
System.out.println("Response2: " + response2);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
希望能够帮到您!
阅读全文