帮我用java和org.apache.http.client.methods.HttpPost写一个发送表单的工具,要求参数是String httpUrl 和Map<String,Object> formData Map<String, String> httpHeader
时间: 2024-04-28 11:27:16 浏览: 138
好的,这里是一个示例代码,可以发送带有表单数据的 POST 请求:
```java
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HttpFormSender {
public static String sendPost(String httpUrl, Map<String,Object> formData, Map<String, String> httpHeader) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(httpUrl);
// 设置请求头
for (String key : httpHeader.keySet()) {
httpPost.setHeader(key, httpHeader.get(key));
}
// 设置表单数据
List<NameValuePair> formParams = new ArrayList<>();
for (String key : formData.keySet()) {
formParams.add(new BasicNameValuePair(key, formData.get(key).toString()));
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8");
httpPost.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(httpPost);
String result = EntityUtils.toString(response.getEntity());
response.close();
httpClient.close();
return result;
}
}
```
使用示例:
```java
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
String httpUrl = "http://example.com/api";
Map<String,Object> formData = new HashMap<>();
formData.put("name", "张三");
formData.put("age", 18);
Map<String, String> httpHeader = new HashMap<>();
httpHeader.put("Content-Type", "application/x-www-form-urlencoded");
try {
String response = HttpFormSender.sendPost(httpUrl, formData, httpHeader);
System.out.println(response);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这个示例代码使用了 Apache HttpComponents 的 HttpClient 来发送请求。你需要先在项目中引入以下 Maven 依赖:
```xml
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
```
阅读全文