package com.han.http;

 import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; public class HttpClientHelp { private final static Logger logger = LoggerFactory.getLogger(HttpClientHelp.class); private final static String ENCODE = "utf-8"; private final static Charset CHARSET = Charset.forName("utf-8");
public static final int TIMEOUT = 20000; private static PoolingHttpClientConnectionManager cm = null;
private static RequestConfig defaultRequestConfig = null; static {
/**
* 连接池管理
* **/
cm = new PoolingHttpClientConnectionManager(); // 将最大连接数
cm.setMaxTotal(50);
// 将每个路由基础的连接增加到20
cm.setDefaultMaxPerRoute(20); /** request设置 **/
// 连接超时 20s
defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).setRedirectsEnabled(false).setSocketTimeout(TIMEOUT)
.setConnectTimeout(TIMEOUT).setConnectionRequestTimeout(TIMEOUT).build();
} public static CloseableHttpClient getClient() {
return HttpClientBuilder.create().setDefaultRequestConfig(defaultRequestConfig).setConnectionManager(cm).build();
} public static String httpGetByUrl(String url) throws ClientProtocolException, IOException {
String responseBody = "";
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpget = new HttpGet(url);
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
@Override
public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
}
};
responseBody = httpclient.execute(httpget, responseHandler);
} finally {
httpclient.close();
}
return responseBody;
} public static String postBodyContent(String url, String bodyContent) throws ClientProtocolException, IOException {
String result = "";
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = null;
try {
HttpPost httppost = new HttpPost(url);
StringEntity reqEntity = new StringEntity(bodyContent, "UTF-8");
httppost.setEntity(reqEntity);
// 设置连接超时5秒,请求超时1秒,返回数据超时8秒
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(1000).setSocketTimeout(8000)
.build();
httppost.setConfig(requestConfig);
response = httpclient.execute(httppost);
HttpEntity responseEntity = response.getEntity();
byte[] bytes = EntityUtils.toByteArray(responseEntity);
result = new String(bytes, "UTF-8");
} finally {
if (null != response) {
response.close();
}
httpclient.close();
}
return result;
} /**
* post paramMap
*
* @param path
* @param params
* @param headers
* @return
*/
public static String post(String path, Map<String, String> params, Map<String, String> headers) {
List<NameValuePair> values = new ArrayList<NameValuePair>();
for (String s : params.keySet()) {
values.add(new BasicNameValuePair(s, params.get(s)));
}
UrlEncodedFormEntity entity = null;
try {
entity = new UrlEncodedFormEntity(values, ENCODE);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
logger.error(e.getMessage());
}
return post(path, entity, headers);
} /**
* post body
*
* @param path
* @param body
* @param headers
* @return
*/
public static String post(String path, String body, Map<String, String> headers) {
return post(path, new StringEntity(body, CHARSET), headers);
} public static String post(String path, HttpEntity postEntity, Map<String, String> headers) {
String responseContent = null;
CloseableHttpClient client = getClient();
HttpPost httpPost = null;
try {
httpPost = new HttpPost(path);
if (headers != null && !headers.isEmpty()) {
for (String s : headers.keySet()) {
httpPost.addHeader(s, headers.get(s));
}
}
httpPost.addHeader("Content-Type", "application/json");
httpPost.setEntity(postEntity);
CloseableHttpResponse response = client.execute(httpPost, HttpClientContext.create());
HttpEntity entity = response.getEntity();
responseContent = EntityUtils.toString(entity, ENCODE);
} catch (Exception e) {
logger.error(e.getMessage());
e.printStackTrace();
} finally {
if (httpPost != null) {
httpPost.releaseConnection();
}
}
return responseContent;
} public static String get(String path, Map<String, String> headers) {
String responseContent = null;
CloseableHttpClient client = getClient();
HttpGet httpGet = new HttpGet(path);
try { if (headers != null && !headers.isEmpty()) {
for (String s : headers.keySet()) {
httpGet.addHeader(s, headers.get(s));
}
}
CloseableHttpResponse response = client.execute(httpGet, HttpClientContext.create());
HttpEntity entity = response.getEntity();
responseContent = EntityUtils.toString(entity, ENCODE);
} catch (Exception e) {
logger.error(e.getMessage());
e.printStackTrace();
} finally {
httpGet.releaseConnection();
}
return responseContent;
} @SuppressWarnings("deprecation")//设置了请求头
public static String postByBodyStringWithHeader(String url, String bodyString) throws ClientProtocolException, IOException {
String result = "";
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = null;
try {
HttpPost httppost = new HttpPost(url);
StringEntity reqEntity = new StringEntity(bodyString, "UTF-8");
httppost.setEntity(reqEntity); Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json;charset=UTF-8");
if (headers != null && !headers.isEmpty()) {
for (String s : headers.keySet()) {
httppost.addHeader(s, headers.get(s));
}
}
//设置连接超时5秒,请求超时1秒,返回数据超时8秒
// RequestConfig requestConfig = RequestConfig.custom()
// .setConnectTimeout(5000).setConnectionRequestTimeout(5000)
// .setSocketTimeout(8000).build();
// httppost.setConfig(requestConfig);
response = httpclient.execute(httppost);
HttpEntity responseEntity = response.getEntity();
byte[] bytes = EntityUtils.toByteArray(responseEntity);
result = new String(bytes,"UTF-8");
} finally {
if (null != response) {
response.close();
}
httpclient.close();
}
return result;
} @SuppressWarnings("deprecation")//没有设置请求头
public static String postByBodyString(String url, String bodyString) throws ClientProtocolException, IOException {
String result = "";
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = null;
try {
HttpPost httppost = new HttpPost(url);
StringEntity reqEntity = new StringEntity(bodyString, "UTF-8");
httppost.setEntity(reqEntity); //设置连接超时5秒,请求超时1秒,返回数据超时8秒
// RequestConfig requestConfig = RequestConfig.custom()
// .setConnectTimeout(5000).setConnectionRequestTimeout(5000)
// .setSocketTimeout(8000).build();
// httppost.setConfig(requestConfig);
response = httpclient.execute(httppost);
HttpEntity responseEntity = response.getEntity();
byte[] bytes = EntityUtils.toByteArray(responseEntity);
result = new String(bytes,"UTF-8");
} finally {
if (null != response) {
response.close();
}
httpclient.close();
}
return result;
} }

JAVA API about HTTP 3的更多相关文章

  1. Atitit 图像处理 调用opencv 通过java  api   attilax总结

    Atitit 图像处理 调用opencv 通过java  api   attilax总结 1.1. Opencv java api的支持 opencv2.4.2 就有了对java api的支持1 1. ...

  2. 【分布式】Zookeeper使用--Java API

    一.前言 上一篇博客我们通过命令行来操作Zookeper的客户端和服务端并进行相应的操作,这篇主要介绍如何通过API(JAVA)来操作Zookeeper. 二.开发环境配置 首先打开Zookeeper ...

  3. Elasticsearch的CRUD:REST与Java API

    CRUD(Create, Retrieve, Update, Delete)是数据库系统的四种基本操作,分别表示创建.查询.更改.删除,俗称"增删改查".Elasticsearch ...

  4. [转]HDFS中JAVA API的使用

    HDFS是一个分布式文件系统,既然是文件系统,就可以对其文件进行操作,比如说新建文件.删除文件.读取文件内容等操作.下面记录一下使用JAVA API对HDFS中的文件进行操作的过程. 对分HDFS中的 ...

  5. HDFS中JAVA API的使用

    HDFS中JAVA API的使用   HDFS是一个分布式文件系统,既然是文件系统,就可以对其文件进行操作,比如说新建文件.删除文件.读取文件内容等操作.下面记录一下使用JAVA API对HDFS中的 ...

  6. java安全沙箱(四)之安全管理器及Java API

    java是一种类型安全的语言,它有四类称为安全沙箱机制的安全机制来保证语言的安全性,这四类安全沙箱分别是: 类加载体系 .class文件检验器 内置于Java虚拟机(及语言)的安全特性 安全管理器及J ...

  7. Java api 入门教程 之 JAVA的Random类

    在实际的项目开发过程中,经常需要产生一些随机数值,例如网站登录中的校验数字等,或者需要以一定的几率实现某种效果,例如游戏程序中的物品掉落等. 在Java API中,在java.util包中专门提供了一 ...

  8. (转)Java API设计清单

    转自: 伯乐在线 Java API设计清单 英文原文 TheAmiableAPI 在设计Java API的时候总是有很多不同的规范和考量.与任何复杂的事物一样,这项工作往往就是在考验我们思考的缜密程度 ...

  9. 【hadoop2.6.0】利用Hadoop的 Java API

    Hadoop2.6.0的所有Java API都在 http://hadoop.apache.org/docs/r2.6.0/api/overview-summary.html 里. 下面实现一个利用J ...

  10. 使用函数库(JAVA API)

    /*使用函数库(JAVA API) * 在JAVA的API里类被封装在一个个的package,要使用package的类之前必须 * 要知道这个类属于哪个package * 引用类方式: * 1.通过i ...

随机推荐

  1. arttemplate 后台返回的数据格式问题

    1. 2.JSON.parse() 方法用于将一个 JSON 字符串转换为对象. $("body").on("click","#analyze&quo ...

  2. 22. Jmeter NON GUI模式

    一般情况下我们都是在NonGUI模式下运行jmeter.这样做有两个好处 节省系统资源,能够产生更大的负载 可以通过命令行参数对测试场景进行更精细的配置 需求:模拟5个用户同时访问百度首页的情况 步骤 ...

  3. MySQL之explain命令解释

    explain显示了mysql如何使用索引来处理select语句以及连接表.可以帮助选择更好的索引和写出更优化的查询语句. 使用方法,在select语句前加上explain就可以了.如: explai ...

  4. 剑指offer——41数组中出现次数超过一半的数字

    题目描述 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字.例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}.由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2. ...

  5. Day 18 :面向对象[基础,继承,组合]类的增删改查

    有的人说,编程有3种范式: 1.面向过程:就是分析出解决问题所需要的步骤,然后用函数把这些步骤一步一步实现,使用的时候一个一个依次调用就可以了. 2.面向函数:面向函数是面向过程的升级版,也就是把每个 ...

  6. jenkins+jhipster集成

    准备工作: 安装Jenkins 新建一个Jhipster项目 开始集成: 新建一个Jenkins构建项目 只配置源代码 构建,成功,稍微有点信心了 配置执行构建脚本 ./mvnw package -P ...

  7. docker mysql 命令导入sql数据文件

    1.查看mysql容器 docker ps 比如我的是:94df84cbaaaa 2.复制sql文件到docker mysql里面的tmp文件夹 docker cp ./admin.sql 94df8 ...

  8. UI自动化ADB出现devices offline的解决方法

    终端运行如下命令即可解决: adb kill-server adb start-server adb remount

  9. 2019-4-12-WPF-类型的构造函数执行符合指定的绑定约束的调用时引发了异常

    title author date CreateTime categories WPF 类型的构造函数执行符合指定的绑定约束的调用时引发了异常 lindexi 2019-04-12 08:52:35 ...

  10. tomcat访问控制及站点部署

    访问控制: 在访问tomcat服务器状态时,出现403错误. 解决方法: [root@localhost ~]# vim /usr/local/tomcat8/conf/tomcat-users.xm ...