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. 动态方法调用秘密武器 —— invokedynamic 指令解读 - MethodHandle

    原文:https://juejin.im/book/5c25811a6fb9a049ec6b23ee/section/5ccc66dd518825403b5975fb import java.lang ...

  2. PAT_A1130#Infix Expression

    Source: PAT A1130 Infix Expression (25 分) Description: Given a syntax tree (binary), you are suppose ...

  3. Git 学习第四天

    我们已经知道,通过命令 git remote add origin git@github.com/Your.name/file.git 可以连接远程仓库,那么,假如我现在想切换另个一远程仓库的连接应该 ...

  4. C# WinForm 第一个项目控件使用心得

    1.控件心得 1.1 基础控件 panel 作用:布局 难点:重绘边框改变颜色 重绘panel里如果有fill填充控件 panle的padding要改个值 private void pnlPaintB ...

  5. mtv 与mvc

    1.MVC与MTV模型 MVC模型 Web服务器开发领域里著名的MVC模式,所谓MVC就是把Web应用分为模型(M),控制器(C)和视图(V)三层,他们之间以一种插件式的.松耦合的方式连接在一起,模型 ...

  6. 自学Oracle心得

    基本术语: global name         全局数据库名 service name        服务名 SID                    实例名 常用命令: 1.       s ...

  7. velocity 相关

    Apache Velocity 是一个基于java的模板引擎(template engine) 应用场景1.Web 应用:开发者在不使用 JSP 的情况下,可以用 Velocity 让 HTML 具有 ...

  8. springboot + zipkin(brave-okhttp实现)

    一.前提 1.zipkin基本知识:附8 zipkin 2.启动zipkin server: 2.1.在官网下载服务jar,http://zipkin.io/pages/quickstart.html ...

  9. OneDrive一直后台占用CPU的一种解决办法

    系统版本:Windows 7 ultimate x64 Onedrive版本:17.3.6998.0830 最近发现Onedrive一直在后台占用15%左右的CPU,很是觉得奇怪,网上的解决方案是删除 ...

  10. JS window对象 History 对象 history对象记录了用户曾经浏览过的页面(URL),并可以实现浏览器前进与后退相似导航的功能。语法: window.history.[属性|方法]

    History 对象 history对象记录了用户曾经浏览过的页面(URL),并可以实现浏览器前进与后退相似导航的功能. 注意:从窗口被打开的那一刻开始记录,每个浏览器窗口.每个标签页乃至每个框架,都 ...