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整理的更多相关文章

  1. HttpClient学习整理

    HttpClient简介HttpClient 功能介绍    1. 读取网页(HTTP/HTTPS)内容    2.使用POST方式提交数据(httpClient3)    3. 处理页面重定向    ...

  2. java apache commons HttpClient发送get和post请求的学习整理(转)

    文章转自:http://blog.csdn.net/ambitiontan/archive/2006/01/06/572171.aspx HttpClient 是我最近想研究的东西,以前想过的一些应用 ...

  3. HttpClient 学习整理【转】

    转自 http://www.blogjava.net/Alpha/archive/2007/01/22/95216.html HttpClient 是我最近想研究的东西,以前想过的一些应用没能有很好的 ...

  4. HttpClient 学习整理

    HttpClient 是我最近想研究的东西,以前想过的一些应用没能有很好的实现,发现这个开源项目之后就有点眉目了,令人头痛的cookie问题还是有办法解决滴.在网上整理了一些东西,写得很好,寄放在这里 ...

  5. HttpClient 学习整理 (转)

    source:http://www.blogjava.net/Alpha/archive/2007/01/22/95216.html HttpClient 是我最近想研究的东西,以前想过的一些应用没能 ...

  6. .Net Standard HttpClient封装Htt请求常用操作整理

    一.常用Http操作 1.Get请求,有参数,无参数 2.Post 请求,有参数,无参数 3.文件简单下载 修改NetHelper中Post请求方法Bug:请求编码默认UTF8,字符串内存流读取后这是 ...

  7. 一:HttpClient知识整理

    一:httpclient 简介 HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支 ...

  8. HttpClient学习整理(一)

    Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且 ...

  9. HttpClient详解,Java发送Http的post、get方式请求 --待整理

    http://www.cnblogs.com/loveyakamoz/archive/2011/07/21/2112804.html http://blog.csdn.net/wangpeng047/ ...

随机推荐

  1. JavaScript 数据结构与算法之美 - 栈内存与堆内存 、浅拷贝与深拷贝

    前言 想写好前端,先练好内功. 栈内存与堆内存 .浅拷贝与深拷贝,可以说是前端程序员的内功,要知其然,知其所以然. 笔者写的 JavaScript 数据结构与算法之美 系列用的语言是 JavaScri ...

  2. 一文看尽Java-Thread

    一.前言      主要分成两部说起:Thread源码解读和常见面试题解答,废话不多说开始: 二.源码解读 首先看下构造函数,构造函数都是通过调用init方法对属性进行初始化,主要是对线程组.线程名字 ...

  3. nginx有哪些作用

    Nginx应该是现在最火的web和反向代理服务器,没有之一.她是一款诞生于俄罗斯的高性能web服务器,尤其在高并发情况下,相较Apache,有优异的表现. 那除了负载均衡,她还有什么其他的用途呢,下面 ...

  4. Timus-1005. Stone Pile-01背包

    传送门:http://acm.timus.ru/problem.aspx?space=1&num=1005 参考:https://www.cnblogs.com/yinzm/p/6629222 ...

  5. 计蒜客 蓝桥杯模拟 瞬间移动 dp

      在一个 n \times mn×m 中的方格中,每个格子上都有一个分数,现在蒜头君从 (1,1)(1,1) 的格子开始往 (n, m)(n,m) 的格子走.要求从 (x_1,y_1)(x1​,y1 ...

  6. codeforces 876 D. Sorting the Coins(线段树(不用线段树写也行线段树写比较装逼))

    题目链接:http://codeforces.com/contest/876/problem/D 题解:一道简单的类似模拟的题目.其实就是看右边连出来有多少连续不需要换的假设位置为pos只要找pos- ...

  7. lightoj 1046 - Rider(bfs)

    A rider is a fantasy chess piece that can jump like a knight several times in a single move. A rider ...

  8. Vue 前端uni-app多环境配置部署服务器的问题

    目录 前端Vue 针对问题 package.json描述 多环境部署 查看源码获取解决方案 转载请标明出处: http://dujinyang.blog.csdn.net/ 本文出自:[奥特曼超人的博 ...

  9. C# 表达式树讲解(一)

    一.前言 一直想写一篇Dpper的定制化扩展的文章,但是里面会设计到对Lambda表达式的解析,而解析Lambda表达式,就必须要知道表达式树的相关知识点.我希望能通过对各个模块的知识点或者运用能够多 ...

  10. SpringCloud入门[转]

    原文链接 一.  网站的架构演变    网络架构由最开始的三层mvc渐渐演变.传统的三层架构后来在互联网公司让几百人几千人同时开发一个项目已经变得不可行,并且会产生代码冲突的问题.基于SOA面向服务开 ...