使用Java来httprequest.post(url)参数是map集合
时间: 2024-03-16 20:44:14 浏览: 99
如果要发送的参数是Map集合,可以使用Java中的`Map.Entry`来遍历Map集合,并将参数拼接成URL编码的字符串。以下是一个示例代码:
```java
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
public class HttpPostExample {
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
HttpPostExample http = new HttpPostExample();
// URL和参数
String url = "http://example.com/api";
Map<String, String> params = Map.of("param1", "value1", "param2", "value2");
// 发送POST请求
String response = http.sendPost(url, params);
System.out.println(response);
}
// 发送POST请求
private String sendPost(String url, Map<String, String> params) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 添加请求头
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
// 将参数拼接成URL编码的字符串
StringBuilder urlParameters = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
if (urlParameters.length() > 0) {
urlParameters.append("&");
}
urlParameters.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
urlParameters.append("=");
urlParameters.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
// 发送POST请求
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters.toString());
wr.flush();
wr.close();
// 获取响应
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();
}
}
```
其中,`sendPost`方法接收URL和Map参数,使用`Map.Entry`遍历Map集合,将参数拼接成URL编码的字符串,并发送POST请求。其他部分与前面的示例代码相同。
阅读全文