需要使用的jar包
- httpcore-4.4.4.jar
- httpclient-4.5.2.jar
- fastjson-1.2.47.jar
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
示例代码
url:请求路径地址
mapdata : 请求携带参数
import org.apache.http.HttpEntity;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.util.*;
public String getContent(String url, Map<String, String> mapdata) {
// System.out.println(url);
// System.out.println(mapdata.toString());
CloseableHttpResponse response = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建httppost
HttpPost httpPost = new HttpPost(url);
try {
// 设置提交方式
httpPost.addHeader("Content-type", "application/x-www-form-urlencoded");
// 添加参数
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
if (mapdata.size() != 0) {
// 将mapdata中的key存在set集合中,通过迭代器取出所有的key,再获取每一个键对应的值
Set keySet = mapdata.keySet();
Iterator it = keySet.iterator();
while (it.hasNext()) {
String k = (String) it.next();// key
String v = mapdata.get(k);// value
nameValuePairs.add(new BasicNameValuePair(k, v));
}
}
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
System.out.println("nameValuePairs:" + nameValuePairs);
// 执行http请求
response = httpClient.execute(httpPost);
// 获得http响应体
HttpEntity entity = response.getEntity();
System.out.println("entity:" + entity);
if (entity != null) {
// 响应的结果
String content = EntityUtils.toString(entity, "UTF-8");
System.out.println("content" + content);
return content;
}
} catch (Exception e) {
e.printStackTrace();
}
return "获取数据错误";
}