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>

HttpClient请求工具类的更多相关文章

  1. 我的Android进阶之旅------>Android关于HttpsURLConnection一个忽略Https证书是否正确的Https请求工具类

    下面是一个Android HttpsURLConnection忽略Https证书是否正确的Https请求工具类,不需要验证服务器端证书是否正确,也不需要验证服务器证书中的域名是否有效. (PS:建议下 ...

  2. java模板模式项目中使用--封装一个http请求工具类

    需要调用http接口的代码继承FundHttpTemplate类,重写getParamData方法,在getParamDate里写调用逻辑. 模板: package com.crb.ocms.fund ...

  3. HttpClientUtils:Http请求工具类

    HttpClientUtils:Http请求工具类 Scala:HttpClientUtils Scala:HttpClientUtils import java.io.IOException imp ...

  4. WebUtils-网络请求工具类

    网络请求工具类,大幅代码借鉴aplipay. using System; using System.Collections.Generic; using System.IO; using System ...

  5. Http、Https请求工具类

    最近在做微信开发,使用http调用第三方服务API,有些是需要https协议,通过资料和自己编码,写了个支持http和https的工具类,经验证可用,现贴出来保留,也供需要的人使用(有不足的地方,也请 ...

  6. 微信https请求工具类

    工作中用到的微信https请求工具类. package com.gxgrh.wechat.tools; import com.gxgrh.wechat.wechatapi.service.System ...

  7. HTTP请求工具类

    HTTP请求工具类,适用于微信服务器请求,可以自测 代码; /// <summary> /// HTTP请求工具类 /// </summary> public class Ht ...

  8. 实现一个简单的http请求工具类

    OC自带的http请求用起来不直观,asihttprequest库又太大了,依赖也多,下面实现一个简单的http请求工具类 四个文件源码大致如下,还有优化空间 MYHttpRequest.h(类定义, ...

  9. 远程Get,Post请求工具类

    1.远程请求工具类   import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.L ...

随机推荐

  1. webservice怎么给对方提供报文,即wsdl文件

    1.webservice发布后在网页打开服务,点击服务说明 2.打开这样一个页面,ctrl+s保存网页,后缀改为wsdl,搞定

  2. Django 学习:为窗体加上防机器人的验证机制(验证码功能)

    这里我们使用 django-simple-captcha 模块,官方介绍如下:https://github.com/mbi/django-simple-captcha 一键安装: pip instal ...

  3. OC - runtime 之关联对象

    header{font-size:1em;padding-top:1.5em;padding-bottom:1.5em} .markdown-body{overflow:hidden} .markdo ...

  4. 【spring】InitializingBean接口

    apollo 源码中有这么一个类 public class ReleaseMessageScanner implements InitializingBean @Override public voi ...

  5. CF886E Maximum Element

    $ \color{#0066ff}{ 题目描述 }$ 从前有一个叫Petya的神仙,嫌自己的序列求max太慢了,于是将序列求max的代码改成了下面这个样子: int fast_max(int n,in ...

  6. 自已的sql server练习小记

    print getdate(); print datediff(year,'1987-09-13',getdate()) select * from CallRecords select top 5 ...

  7. WPF:CheckBox竖向的滑块效果

    原文:WPF:CheckBox竖向的滑块效果 之前做了一个横向的滑块效果,<WPF:CheckBox滑块效果>,其实我觉得那个不好看,今天又做了一个竖向的玩. <Style Targ ...

  8. EasyUI学习笔记(三)—— message和menubutton的使用

    一.message(消息框) 1.1 alert   <script type="text/javascript"> $(function () { // alert方 ...

  9. 安装Linux虚拟机到执行Java程序

    1.安装VMware 2.在VMware里安装 CentOs 镜像(CentOS-7.2-x86_64-DVD-1511.iso) 3.启动CentOs后如果不能上网,或者 没有 ifconfig命令 ...

  10. 爬虫之自动生成url

    Object.extend=function(props){ //继承父类 var prototype=Object.create(this.prototype) //初始化函数ctor var _C ...