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. 浏览器获取自定义响应头response-headers

    原创作品版权归属本人所有,违者必究 https://blog.csdn.net/qq_37025445/article/details/82888731想在浏览器获取响应头里面自定义的响应头:file ...

  2. 引入scss(@import)和其中易错点

    1.引入文件方式 @import 'url'; ./ :当前目录 ../ :上级目录 src/api/styles: 绝对路径 2.一般在main.js中引用当做全局样式 import 'styles ...

  3. 『Golang』—— 标准库之 time

    ... package main import ( "fmt" "time" ) func main() { time.AfterFunc(time.Milli ...

  4. vue项目使用js-xlsx进行excel表格的导入和导出方法的简单原型封装

    前提:已经安装好 file-saver xlsx和 script-loader,如未安装,请查看 https://www.cnblogs.com/luyuefeng/p/8031597.html 新建 ...

  5. node+webpack+vue的环境搭建

      一般第一次搭建环境的时候,多多少少还是会出点状况的.这个时候多去百度,看牛人怎么解决,然后跟着尝试,多试几遍还是能解决的. 先说一下我安装的过程吧 1.我一开始按照官网的来搭建,失败了.报错内容是 ...

  6. JS 将对象转换成字符 字符串转换成json对象

    //js对象 var user = { "name": "张学友", "address": "中国香港" }; //将对 ...

  7. 微信小程序之评分页面

    首先给大家看看做好的效果图: 一.接下来我们说一下评分这个功能: 实际上就是一个简单的js,首先我们遍历出小星星,此时默认给的五星好评,在给他们一个点击事件,当点击时,我们获取到当前点击的是第几颗:代 ...

  8. UTF-8 - ASCII 兼容的多字节 Unicode 编码

    描述 The Unicode 字符集使用的是 16 位(双字节)码.最普遍的 Unicode 编码方法( UCS-2) 由一个 16 位双字序列组成.这样的字符串中包括了的一些如‘\0’或‘/’这样的 ...

  9. 笔记:Python的浅复制和深复制

    方法copy返回一个新字典,其包含的键-值对与原来的字典相同(这个方法执行的是浅复制,因为值本身是原件,而不是副本). >>> x = {"username": ...

  10. JS对象 编程练习 某班的成绩出来了,现在老师要把班级的成绩打印出来。 效果图: XXXX年XX月X日 星期X--班级总分为:81

    编程练习 某班的成绩出来了,现在老师要把班级的成绩打印出来. 效果图: XXXX年XX月X日 星期X--班级总分为:81 格式要求: 1.显示打印的日期. 格式为类似"XXXX年XX月XX日 ...