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(); }
}

最新文章

  1. 【BZOJ-3039&amp;1057】玉蟾宫&amp;棋盘制作 悬线法
  2. 湖南省第十二届大学生计算机程序设计竞赛 G Parenthesis
  3. dstat 备忘
  4. C++中数组求偏移量计算公式
  5. sql sever 2000
  6. 八大排序方法汇总(选择排序,插入排序-简单插入排序、shell排序,交换排序-冒泡排序、快速排序、堆排序,归并排序,计数排序)
  7. 数据挖掘方面重要会议的最佳paper集合
  8. UVALive 4992 Jungle Outpost(半平面交)
  9. 分享几个日常调试方法让js调试更简单
  10. jenkins管理员密码登录不了
  11. 采用集成的Windows验证和使用Sql Server身份验证进行数据库的登录
  12. Python&#160;基于python+mysql浅谈redis缓存设计与数据库关联数据处理
  13. iOS数据库操作之coredata详细操作步骤
  14. VS2015 之 多行缩进
  15. yum安装docker报 No package docker available错误
  16. LCS,LIS,LCIS学习
  17. 我所理解的网络游戏&lt;一&gt;:网游的顶层设计
  18. nginx pcre错误
  19. 简单的 Android 菜单
  20. MyEclipse2015创建配置Web+Maven项目

热门文章

  1. c++ 开发JNI
  2. F#周报2019年第35期
  3. vue.js如何根据后台返回来的图片url进行图片下载
  4. 知识图谱推理与实践 (2) -- 基于jena实现规则推理
  5. UVA 11294 wedding 2-sat
  6. Atcode B - Colorful Hats(思维)
  7. 【LeetCode】322-零钱兑换
  8. Python作业本——第5章 字典和结构化数据
  9. Springboot源码分析之TypeFilter魔力
  10. javascript合并两个数组