package com.yangche.utils;

 import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
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 org.springframework.util.StringUtils; import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; public class HttpClientUtil {
public static String doGet(String url, Map<String,Object> param){
//创建httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
String resultString="";
CloseableHttpResponse response=null;
try {
URIBuilder builder=new URIBuilder(url);
if(param!=null){
for (String key:param.keySet()){
if(param.get(key) instanceof List){
List list=(List)param.get(key);
for (Object liString:list){
builder.addParameter(key,String.valueOf(liString));
}
}else {
builder.addParameter(key,String.valueOf(param.get(key)));
}
}
}
URI uri=builder.build();
//创建httpGet请求
HttpGet httpGet=new HttpGet(uri);
//执行请求
response=httpClient.execute(httpGet);
resultString= EntityUtils.toString(response.getEntity(),"UTF-8");
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(response!=null){
response.close();
}
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doGet(String url){
return doGet(url,null);
}
public static String doPost(String url,Map<String,String> param){
//创建httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response=null;
String resultString="";
//创建httpPost请求
HttpPost httpPost = new HttpPost(url);
//创建参数列表
if(param!=null){
List<NameValuePair> paramList=new ArrayList<>();
for (String key:param.keySet()){
paramList.add(new BasicNameValuePair(key,param.get(key)));
}
try {
//模拟表单
UrlEncodedFormEntity entity=new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
//执行http请求
response=httpClient.execute(httpPost);
resultString=EntityUtils.toString(response.getEntity(),"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return resultString;
}
public static String doPost(String url){
return doPost(url,null);
} /**
* restful请求
* @param url
* @param requestType 请求类型:post、delete、patch
* @param json
* @return
*/
public static String doRequest(String url,String requestType,String json){
//创建HttpClient对象
CloseableHttpClient httpClient=HttpClients.createDefault();
CloseableHttpResponse response=null;
String resultString="";
try {
//创建不同类型的请求
HttpPost httpPost=new HttpPost(url);
HttpDeleteWithBody httpDelete =new HttpDeleteWithBody(url);
HttpPatch httpPatch=new HttpPatch(url);
//创建请求内容
StringEntity entity=new StringEntity(json, ContentType.APPLICATION_JSON);
//执行http请求
if(!StringUtils.isEmpty(requestType)&&requestType.equalsIgnoreCase("post")){
httpPost.setEntity(entity);
response=httpClient.execute(httpPost);
}else if(!StringUtils.isEmpty(requestType)&&requestType.equalsIgnoreCase("delete")){
httpDelete.setEntity(entity);
response=httpClient.execute(httpDelete);
}else if(!StringUtils.isEmpty(requestType)&&requestType.equalsIgnoreCase("patch")){
httpPatch.setEntity(entity);
response=httpClient.execute(httpPatch);
}
resultString=EntityUtils.toString(response.getEntity(),"UTF-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
} private static class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
public static final String METHOD_NAME="DELETE";
@Override
public String getMethod() {
return METHOD_NAME;
}
public HttpDeleteWithBody (final String uri){
super();
setURI(URI.create(uri));
}
public HttpDeleteWithBody (final URI uri){
super();
setURI(uri);
}
public HttpDeleteWithBody(){
super();
}
}
}
以上所需的maven依赖如下:
 <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.10</version>
</dependency> <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>

最新文章

  1. 配置与使用 Git与Github
  2. BookBlock - 效果非常真实的书本翻页预览
  3. python peewee.ImproperlyConfigured: MySQLdb or PyMySQL must be installed.
  4. kaili linux中文乱码
  5. BZOJ3828 : [Poi2014]Criminals
  6. C#对XML、JSON等格式的解析
  7. Ajax - 登录
  8. 基于.NET MVC的高性能IOC插件化架构
  9. ios的位置和方向(来自苹果官方文档,仅供简单参考)
  10. struts2框架学习笔记3:获取servletAPI
  11. elk系统通过nginx添加对kibana的登录认证
  12. 域名直接访问应用程序-不加端口号&amp;不加路径名
  13. ssm controller层 junit单元测试
  14. OpenLayers 比较有用的对象和属性
  15. python pytest测试框架介绍四----pytest-html插件html带错误截图及失败重测机制
  16. c语言格式大整理
  17. POJ 1836 Alignment (双向DP)
  18. BZOJ2820 YY的GCD 【莫比乌斯反演】
  19. POJ2142(扩展欧几里得)
  20. Python 利用循环画散点图

热门文章

  1. struts2的主要工作流程
  2. I/O(输入/输出)---File类
  3. js 对象 浅拷贝 和 深拷贝
  4. django bug 与陷阱
  5. 【问题记录】element is not attached to the page document
  6. 没有上司的舞会 树形dp
  7. TX2 上使用opencv 调用板载mipi摄像头
  8. 移动像素的px ,dp/pt,dpr的关系
  9. 数据库,asp总结思维导图图片
  10. 正则表达式中模式修正符作用详解(i、g、m、s、x、e)