Java代码:具有header,url,请求参数,调用方式(get或者post)的http调用类
时间: 2023-05-19 13:07:33 浏览: 309
以下是一个简单的 Java http 调用类,具有 header、url、请求参数和调用方式(get 或 post):
```
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
public class HttpUtil {
public static String sendHttpRequest(String url, Map<String, String> headers, Map<String, String> params, String method) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法
con.setRequestMethod(method);
// 设置请求头
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
con.setRequestProperty(entry.getKey(), entry.getValue());
}
}
// 设置请求参数
if (params != null && method.equalsIgnoreCase("post")) {
con.setDoOutput(true);
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
}
byte[] postDataBytes = sb.toString().getBytes("UTF-8");
con.getOutputStream().write(postDataBytes);
}
// 发送请求
int responseCode = con.getResponseCode();
// 读取响应
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
}
```
你可以使用该类来发送 HTTP 请求,例如:
```
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
Map<String, String> params = new HashMap<>();
params.put("username", "test");
params.put("password", "123456");
String response = HttpUtil.sendHttpRequest("http://example.com/login", headers, params, "post");
System.out.println(response);
```
这将发送一个 POST 请求到 `http://example.com/login`,并带有 `Content-Type: application/json` 的请求头和 `username=test&password=123456` 的请求参数。
阅读全文