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 ...
随机推荐
- 【bzoj3329】Xorequ 矩阵快速幂
Description Input 第一行一个正整数,表示数据组数据 ,接下来T行 每行一个正整数N Output 2T行 第2i-1行表示第i个数据中问题一的解, 第2*i行表示第i个数据中问题二的 ...
- vue的生命周期钩子函数
一.vue生命周期图示 二.钩子函数执行时间 beforeCreate 在创建实例之前,data只声明但没有赋值 在实例初始化之后,数据观测 (data observer) 和 event ...
- System.Security.Cryptography.CryptographicException
在调用System.Security.Cryptography.ProtectedData.Protect方法来保护私密信息时,IIS可能会报以下错误:CryptographicException: ...
- hdp 2.06 安装备忘
1,官方安装说明文档 http://docs.hortonworks.com/HDPDocuments/HDP2/HDP-2.0.6.0-Win/bk_installing_hdp_for_windo ...
- jquery遇到的坑
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- SGU - 275 线性基 初步
题意:求给出的数任意异或的最大值 目前对线性基的理解过于肤浅,有空总结一下 #include<iostream> #include<algorithm> #include< ...
- vim大法
$Linux vi/vim编辑器常用命令与用法总结 (一)vi/vim是什么?Linux世界几乎所有的配置文件都是以纯文本形式存在的,而在所有的Linux发行版系统上都有vi编辑器,因此利用简单的文字 ...
- PIE SDK栅格分级渲染
1. 功能简介 栅格数据分级渲染是根据不同的分级规则,对像元值进行等级划分:并通过对每一级设置不同的显示符号和标注信息,从而达到分级显示的效果. 2.功能实现说明 2.1. 实现思路及原理说明 第一 ...
- my32_ error 1872 Slave failed to initialize relay log info structure from the repository
重启了实例后,slave进程无法开启 Last_SQL_Errno: Last_SQL_Error: Slave failed to initialize relay log info structu ...
- pipline --学习 (-)
一,语法: 编写位置: pipline 启动docker pipeline { agent { docker 'maven:3.3.3' } stages { stage('build') { ste ...