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. python之lambda,random,timeit,collections,

    python之lambda,random,timeit,collections,一. python之lambda函数lambda函数又称为匿名函数,匿名函数就是没有函数名的函数.>>> ...

  2. 谈谈-Android Studio 调试功能

    先编译好要调试的程序. 1.设置断点 选定要设置断点的代码行,在行号的区域后面单击鼠标左键即可. 2.开启调试会话 点击红色箭头指向的小虫子,开始进入调试. IDE下方出现Debug视图,红色的箭头指 ...

  3. Jeecg 3.8修改lhgDialog弹窗的样式

    位置:F:\jeecg-bpm-3.8\eecg-bpm-3.8-master\jeecg-bpm-3.8\src\main\java\org\jeecgframework\core\util pub ...

  4. 3.4 redux 异步

    在大多数的前端业务场景中,需要和后端产生异步交互,在本节中,将详细讲解 redux 中的异步方案以及一些异步第三方组件,内容有: redux 异步流 redux-thunk redux-promise ...

  5. HDU 6695 Welcome Party (贪心)

    2019 杭电多校 10 1005 题目链接:HDU 6695 比赛链接:2019 Multi-University Training Contest 10 Problem Description T ...

  6. 关于 CShellManager 的作用

    也许大家看到这个题目,未曾进行windows shell编程的同学呢,会不明白是什么意思,这里简单的介绍一下,windows shell就是可以使编写的程序与系统关联(如快捷方式,托盘图标等),管理系 ...

  7. 20140730 word标题样式 数组

    1.word 标题四, 右键更新 自己也可以新建标题样式 2.数组 连续内存,空间复杂度高(即使数组存在一个元素,占据的空间的大小不变),时间复杂度低(0(1)访问),内存分配一次性完成

  8. python:异常处理及程序调试

    1.异常概述 在程序运行过程中,经常会遇到各种各样的错误.这些错误统称为“异常”,在这些一场中有的是由于开发者将关键词写错导致,这类错误产生的是SyntaxError.invalid syntax(无 ...

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

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

  10. pytest_fixture-----conftest共享数据及不同层次共享

    场景:你与其他测试工程师合作一起开发时,公共的模块要在不同文件中,要 在大家都访问到的地方. 解决:使用conftest.py 这个文件进行数据共享,并且他可以放在不同位置起 着不同的范围共享作用. ...