httpclient整理
package com.yjl.util; import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
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.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Created by Administrator on 2018/4/27.
*/
public class HttpClientUtil { final static String authorValue =
"eyJhbGciOiJSUzI1NiIsImtpZCI6IjRDNTQwNzlDQTU4OUZDRUREMTg5NzYzRUZBQTU4MTUzNTQ5MUNCOEMiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJURlFIbktXSl9PM1JpWFktLXFXQlUxU1J5NHcifQ.eyJuYmYiOjE1NTQyNjAxODIsImV4cCI6MTU1NDQzMjk4MiwiaXNzIjoiaHR0cDovL29hdXRoOjQwMDAiLCJhdWQiOlsiaHR0cDovL29hdXRoOjQwMDAvcmVzb3VyY2VzIiwib3BlbmFwaSJdLCJjbGllbnRfaWQiOiJhcHAuc2RrLnJlZnJlc2giLCJzdWIiOiItMSIsImF1dGhfdGltZSI6MTU1NDI2MDE4MiwiaWRwIjoibG9jYWwiLCJlY29kZSI6IkUwMDE4OTgwIiwibG9naW5fbmFtZSI6IkUwMDE4OTgwIiwiaWRlbnRpZmljYXRpb24iOiIiLCJzY29wZSI6WyJvcGVuYXBpIiwib2ZmbGluZV9hY2Nlc3MiXSwiYW1yIjpbImVudGVycHJpc2VfYXBwIl19.fuEnQiB2xgMX5CG1UFY_9bUxjpzx8eKHHlb6fIc1_JgPDn45DhLNU1gNO_oLE4_jkThpR0WeotxYGgU3iv-9myOZWlWGfH1ClOfL7JR8jEATp0VYTWNpA8SQ5wDmbq-MnKcqVIxsFUXH1EVrW0pd_lc6eRHfTHkgJPrutBEstVoeFCOuNo2iCBtswV9yaZroJTBq-FPgEBHphS4Q4TotcO_vE3oD6qFrXs2w9-Ln3C0bLftxnEFcsO_iKIYb3K6VOSZACKPW7djI5w_U7Oj-2jR0ULGpF43J983NksenTMP4LW4oU4KjNy0RxHbNsbvT-Y8lN3oE0SwnAOeAPk5QCkfhAXaHOwLXNCiqYxABG0sWWHztuJkkxgcCVmVDwCSuIWhL5DFVJCN-IEirFXhvhLznV9ym9wxvz0xE84uVVEtx4KL8-z0E0Fcf3vYAGLuC8_QD3oyG1V81x0G7rNPrK-UomAYkRH1ZCn0KhLR3KzqzGbNUcGlpJrnJze1KJd6ZNY0Z3J_4zK3UaMf5TdryU18pfKB8ZOo3I7tM4eer6MNPNBvSu-gA_DGNDyXmpSNgtoCLAprc9UHjgiALybJGbeQCj_z2nEkXX9Aw9EpwguOVdQvLjvyD_ul_yOK3VPiZmKQHOy9jwz8GyqW2iO1UNIMbrRc3_RZ_DrR-R6CHPK0";
public static String doGet(String url, Map<String, String> param) { // 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault(); String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build(); // 创建http GET请求
HttpGet httpGet = new HttpGet(uri); // 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == ) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
} /**
* get 请求
* @param url
* @param authorValue
* @param para
* @return
*/
public static JSONObject doGetJson(String url, String authorValue, Map<String, String> para){
JSONObject response = null;
try{
HttpClient client = new DefaultHttpClient(); URIBuilder builder = new URIBuilder(url);
Set<String> set = para.keySet();
for(String key: set){
builder.setParameter(key, para.get(key));
}
HttpGet request = new HttpGet(builder.build());
if(StringUtils.isNotEmpty(authorValue)){
request.setHeader("Authorization",authorValue);
}
request.setHeader("ContentTye","application/json");
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout()
.setConnectTimeout()
.setConnectionRequestTimeout().build();
request.setConfig(requestConfig); HttpResponse res = client.execute(request);
// if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
HttpEntity entity = res.getEntity();
String result = EntityUtils.toString(res.getEntity());// 返回json格式:
response = JSONObject.fromObject(result);
// }
} catch (Exception e) {
throw new RuntimeException(e);
}
return response;
} 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 = "";
try {
// 创建Http Post请求
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)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8");
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} return resultString;
} public static String doPostJson(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
httpPost.setHeader("Content-Type","application/json");
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} return resultString;
} public static String doPostJsonToAnLian(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
String token = "Bearer "+authorValue;
if(StringUtils.isNotEmpty(authorValue)){
httpPost.addHeader("Authorization",token);
}
httpPost.addHeader("Content-Type","application/json");
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return resultString;
} public static String doPutJsonToAnLian(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Put请求
HttpPut httpPut = new HttpPut(url);
String token = "Bearer "+authorValue;
if(StringUtils.isNotEmpty(authorValue)){
httpPut.addHeader("Authorization",token);
}
httpPut.addHeader("Content-Type","application/json");
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPut.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPut);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return resultString;
} public static String doDeleteJsonToAnLian(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Delete请求
HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url);
String token = "Bearer "+authorValue;
if(StringUtils.isNotEmpty(authorValue)){
httpDelete.addHeader("Authorization",token);
}
httpDelete.addHeader("Content-Type","application/json");
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpDelete.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpDelete);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return resultString;
}
} /**
* 内部类,删除调用+传参
*/
@NotThreadSafe
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(); }
}
httpclient整理的更多相关文章
- HttpClient学习整理
HttpClient简介HttpClient 功能介绍 1. 读取网页(HTTP/HTTPS)内容 2.使用POST方式提交数据(httpClient3) 3. 处理页面重定向 ...
- java apache commons HttpClient发送get和post请求的学习整理(转)
文章转自:http://blog.csdn.net/ambitiontan/archive/2006/01/06/572171.aspx HttpClient 是我最近想研究的东西,以前想过的一些应用 ...
- HttpClient 学习整理【转】
转自 http://www.blogjava.net/Alpha/archive/2007/01/22/95216.html HttpClient 是我最近想研究的东西,以前想过的一些应用没能有很好的 ...
- HttpClient 学习整理
HttpClient 是我最近想研究的东西,以前想过的一些应用没能有很好的实现,发现这个开源项目之后就有点眉目了,令人头痛的cookie问题还是有办法解决滴.在网上整理了一些东西,写得很好,寄放在这里 ...
- HttpClient 学习整理 (转)
source:http://www.blogjava.net/Alpha/archive/2007/01/22/95216.html HttpClient 是我最近想研究的东西,以前想过的一些应用没能 ...
- .Net Standard HttpClient封装Htt请求常用操作整理
一.常用Http操作 1.Get请求,有参数,无参数 2.Post 请求,有参数,无参数 3.文件简单下载 修改NetHelper中Post请求方法Bug:请求编码默认UTF8,字符串内存流读取后这是 ...
- 一:HttpClient知识整理
一:httpclient 简介 HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支 ...
- HttpClient学习整理(一)
Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且 ...
- HttpClient详解,Java发送Http的post、get方式请求 --待整理
http://www.cnblogs.com/loveyakamoz/archive/2011/07/21/2112804.html http://blog.csdn.net/wangpeng047/ ...
随机推荐
- Codeforces Round #486 (Div. 3)988E. Divisibility by 25技巧暴力||更暴力的分类
传送门 题意:给定一个数,可以对其做交换相邻两个数字的操作.问最少要操作几步,使得可以被25整除. 思路:问题可以转化为,要做几次交换,使得末尾两个数为00或25,50,75: 自己一开始就是先for ...
- yzoj 1201数字三角形3题解
题意 如下图所示为一个数字三角形: 7 3 8 8 1 0 2 7 4 4 4 5 2 6 5 请编程计算从顶至底部某处的一条路径,使该路径所经过的数字的总和最大.约定: (1)每一步可沿直线向下或右 ...
- R:ggplot2数据可视化——进阶(1)
,分为三个部分,此篇为Part1,推荐学习一些基础知识后阅读~ Part 1: Introduction to ggplot2, 覆盖构建简单图表并进行修饰的基础知识 Part 2: Customiz ...
- Java内部类的使用小结 形参为什么要用final
部类是指在一个外部类的内部再定义一个类.类名不需要和文件夹相同. *内部类可以是静态static的,也可用public,default,protected和private修饰.(而外部顶级类即类名和文 ...
- 实现一个基于码云Storage
实现一个简单的基于码云(Gitee) 的 Storage Intro 上次在 asp.net core 从单机到集群 一文中提到存储还不支持分布式,并立了一个 flag 基于 github 或者 开源 ...
- mysql之innodb存储引擎介绍
一.Innodb体系架构 1.1.后台线程 后台任务主要负责刷新内存中的数据,保证缓冲池的数据是最近的数据,此外还将修改的数据刷新到文件磁盘,保证在数据库发生异常的情况下Innodb能恢复到正常的运行 ...
- BigDecimal转String
代码: public static void main(String[] args) { // 浮点数的打印 System.out.println(new BigDecimal("10000 ...
- Maven学习归纳(二)——几个常用命令解析
Maven的常用命令 第一次执行命令的时候,因为需要下载执行命令的基础环境,所以会从远程仓库下载该环境到本地仓库中 运行mvn命令,必须在pom.xml文件所在的目录 一. JavaProject的p ...
- Kafka源码分析及图解原理之Broker端
一.前言 https://www.cnblogs.com/GrimMjx/p/11354987.html 上一节说过,任何消息队列都是万变不离其宗都是3部分,消息生产者(Producer).消息消费者 ...
- xshell使用小技巧
1. 方便复制:Tool --> options --> right buttion(paste the clipboard contents) and copy selected te ...