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 小游戏 贪吃蛇

    贪吃蛇 代码: <!DOCTYPE html><html><head> <meta charset="UTF-8"> <met ...

  2. k8s集群部分常见问题处理

    目录 部分常见问题处理 Coredns CrashLoopBackOff 导致无法成功添加工作节点的问题 添加工作节点时提示token过期 kubectl 执行命令报“The connection t ...

  3. Windows Server 2008 R2

    Windows Server 2008 R2 Windows Server Core 微软因为向往 Linux 的纯命令行, 提出了 Windows Server Core 只能使用命令, 但是只要配 ...

  4. 2019icpc徐州网络赛_I_query

    题意 给定一个序列,多次询问区间\([l,r]\)中满足\(min(a[i],a[j])==gcd(a[i],a[j])\)的数对\((i,j)\)数. 分析 其实就是求区间有倍数关系的数对数. 由于 ...

  5. Java 添加Word文本框

    在Word中,文本框是指一种可移动.可调节大小的文字或图形容器.我们可以向文本框中添加文字.图片.表格等对象,下面,将通过Java编程来实现添加以上对象到Word文本框. 使用工具:Free Spir ...

  6. 【Offer】[22] 【链表中倒数第k个结点】

    题目描述 思路分析 测试用例 Java代码 代码链接 题目描述 输入一个链表,输出该链表中倒数第k个结点. 思路分析 采用双指针的方法,第一个指针首先向前移动k-1个位置,第二个指针指向头节点,然后将 ...

  7. 脱离脚手架来配置、学习 webpack4.x (一)基础搭建项目

    序 现在依旧记得第一次看到webpack3.x 版本配置时候的状态  刚开始看到这些真的是一脸懵.希望这篇文章能帮到刚开始入门的同学. webpack 是什么? webpack是一个模块化打包工具,w ...

  8. Accuarcy and Precision

    机器学习中,Accuarcy 和 Precision 有什么区别呢? Accuracy = (TP+TN)/TOTAL SAMPLES 也就是计算正确的样本数,占到总样本数的比率 定义是: 对于给定的 ...

  9. QRowTable表格控件(五)-重写表头排序、支持第三次单击恢复默认排序

    目录 一.原生表格 二.效果展示 三.实现方式 1.排序列定制 2.排序交互修改 四.相关文章 原文链接:QRowTable表格控件(五)-重写表头排序.支持第三次单击恢复默认排序 一.原生表格 开发 ...

  10. 虚拟化(三) -vsphere套件的安装注意及使用

    https://www.cnblogs.com/zhrngM/p/9547958.html [转]虚拟化(三):vsphere套件的安装注意及使用 vsphere套件里面主要的组件有esxi.vcen ...