HttpClient请求工具类
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请求工具类的更多相关文章
- 我的Android进阶之旅------>Android关于HttpsURLConnection一个忽略Https证书是否正确的Https请求工具类
下面是一个Android HttpsURLConnection忽略Https证书是否正确的Https请求工具类,不需要验证服务器端证书是否正确,也不需要验证服务器证书中的域名是否有效. (PS:建议下 ...
- java模板模式项目中使用--封装一个http请求工具类
需要调用http接口的代码继承FundHttpTemplate类,重写getParamData方法,在getParamDate里写调用逻辑. 模板: package com.crb.ocms.fund ...
- HttpClientUtils:Http请求工具类
HttpClientUtils:Http请求工具类 Scala:HttpClientUtils Scala:HttpClientUtils import java.io.IOException imp ...
- WebUtils-网络请求工具类
网络请求工具类,大幅代码借鉴aplipay. using System; using System.Collections.Generic; using System.IO; using System ...
- Http、Https请求工具类
最近在做微信开发,使用http调用第三方服务API,有些是需要https协议,通过资料和自己编码,写了个支持http和https的工具类,经验证可用,现贴出来保留,也供需要的人使用(有不足的地方,也请 ...
- 微信https请求工具类
工作中用到的微信https请求工具类. package com.gxgrh.wechat.tools; import com.gxgrh.wechat.wechatapi.service.System ...
- HTTP请求工具类
HTTP请求工具类,适用于微信服务器请求,可以自测 代码; /// <summary> /// HTTP请求工具类 /// </summary> public class Ht ...
- 实现一个简单的http请求工具类
OC自带的http请求用起来不直观,asihttprequest库又太大了,依赖也多,下面实现一个简单的http请求工具类 四个文件源码大致如下,还有优化空间 MYHttpRequest.h(类定义, ...
- 远程Get,Post请求工具类
1.远程请求工具类 import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.L ...
随机推荐
- 安装jdk1.8,编写环境变量
好记性不如烂笔头!!!(我这是把jdk放在的/usr/local下,且命令为jdk1.8...复制的时候别搞错位置了) JAVA_HOME=/usr/local/jdk1./ JAVA_BIN=/us ...
- 吴裕雄 python 机器学习——密度聚类DBSCAN模型
import numpy as np import matplotlib.pyplot as plt from sklearn import cluster from sklearn.metrics ...
- [PowerShell]Quote in String
今天遇到一个问题,如何在Select-String的Pattern参数里能使用双引号 比如 Select-String -path . -pattern "Lines: <span c ...
- python学习,day2:列表的复制
主要涉及列表的潜复制(第二层受后面修改的影响)和深复制(不受后面修改的影响) 代码如下 # coding=utf-8 # Author: RyAn Bi import copy names = ['A ...
- C++_类和动态内存分配1—动态内存和类
静态类成员 num_strings成员声明为静态存储类.静态类成员有一个特点:无论创建了多少对象,程序都只创建一个静态类变量副本.也就是说,类的所有对象共享一个静态成员.num_strings成员可以 ...
- 教你搭建SpringSecurity3框架(附源码)
源码下载地址:http://pan.baidu.com/s/1qWsgIg0 一.web.xml <?xml version="1.0" encoding="UTF ...
- [BZOJ 3262]陌上开花
今天写了到偏序问题,发现博主真的是个傻X 传送门 以前的写法 /************************************************************** Probl ...
- npm 安装命令中的参数 --save-dev
为项目安装模块的npm命令一般是—— npm i module-name 执行完毕后,需要手动把模块名称连同版本号一同的添加到模块配置文件package.json中的依赖里(dependencies) ...
- 我所理解的session_set_save_handler的执行顺序机制
默认的session handler启动顺序 <?php ini_set('session.gc_maxlifetime',10); ini_set('session.gc_probabilit ...
- [转] 前后端分离之JWT用户认证
[From] http://www.jianshu.com/p/180a870a308a 在前后端分离开发时为什么需要用户认证呢?原因是由于HTTP协定是不储存状态的(stateless),这意味着当 ...