上面这个方法params不要string类型,改成Map<String, String>类型
时间: 2023-11-18 09:52:13 浏览: 65
Flutter实现网络请求的方法示例
5星 · 资源好评率100%
好的,以下是修改后的Java HTTP工具类,可以发送GET请求并将参数放在请求体中:
```java
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;
public class HttpUtils {
public static String sendGetRequest(String url, Map<String, String> params) throws IOException {
HttpURLConnection con = null;
OutputStream os = null;
try {
URL obj = new URL(url);
con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "application/json");
con.setDoOutput(true);
os = con.getOutputStream();
os.write(getBytes(params));
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
return new String(con.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
}
} finally {
if (os != null) {
os.close();
}
if (con != null) {
con.disconnect();
}
}
return null;
}
private static byte[] getBytes(Map<String, String> params) throws IOException {
StringBuilder result = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
if (result.length() > 0) {
result.append("&");
}
result.append(entry.getKey());
result.append("=");
result.append(entry.getValue());
}
return result.toString().getBytes(StandardCharsets.UTF_8);
}
}
```
使用方法如下:
```java
String url = "http://example.com/api";
Map<String, String> params = new HashMap<>();
params.put("key1", "value1");
params.put("key2", "value2");
String response = HttpUtils.sendGetRequest(url, params);
```
其中,`url`是请求的URL地址,`params`是一个`Map<String, String>`类型的对象,用于存放请求参数。这个工具类使用了Java自带的HttpURLConnection类来发送HTTP请求,并且将参数放在请求体中。注意,这里的`Content-Type`是`application/json`,如果请求体格式不同,需要相应地进行修改。
阅读全文