JAVA API about HTTP 3
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的更多相关文章
- Atitit 图像处理 调用opencv 通过java api attilax总结
Atitit 图像处理 调用opencv 通过java api attilax总结 1.1. Opencv java api的支持 opencv2.4.2 就有了对java api的支持1 1. ...
- 【分布式】Zookeeper使用--Java API
一.前言 上一篇博客我们通过命令行来操作Zookeper的客户端和服务端并进行相应的操作,这篇主要介绍如何通过API(JAVA)来操作Zookeeper. 二.开发环境配置 首先打开Zookeeper ...
- Elasticsearch的CRUD:REST与Java API
CRUD(Create, Retrieve, Update, Delete)是数据库系统的四种基本操作,分别表示创建.查询.更改.删除,俗称"增删改查".Elasticsearch ...
- [转]HDFS中JAVA API的使用
HDFS是一个分布式文件系统,既然是文件系统,就可以对其文件进行操作,比如说新建文件.删除文件.读取文件内容等操作.下面记录一下使用JAVA API对HDFS中的文件进行操作的过程. 对分HDFS中的 ...
- HDFS中JAVA API的使用
HDFS中JAVA API的使用 HDFS是一个分布式文件系统,既然是文件系统,就可以对其文件进行操作,比如说新建文件.删除文件.读取文件内容等操作.下面记录一下使用JAVA API对HDFS中的 ...
- java安全沙箱(四)之安全管理器及Java API
java是一种类型安全的语言,它有四类称为安全沙箱机制的安全机制来保证语言的安全性,这四类安全沙箱分别是: 类加载体系 .class文件检验器 内置于Java虚拟机(及语言)的安全特性 安全管理器及J ...
- Java api 入门教程 之 JAVA的Random类
在实际的项目开发过程中,经常需要产生一些随机数值,例如网站登录中的校验数字等,或者需要以一定的几率实现某种效果,例如游戏程序中的物品掉落等. 在Java API中,在java.util包中专门提供了一 ...
- (转)Java API设计清单
转自: 伯乐在线 Java API设计清单 英文原文 TheAmiableAPI 在设计Java API的时候总是有很多不同的规范和考量.与任何复杂的事物一样,这项工作往往就是在考验我们思考的缜密程度 ...
- 【hadoop2.6.0】利用Hadoop的 Java API
Hadoop2.6.0的所有Java API都在 http://hadoop.apache.org/docs/r2.6.0/api/overview-summary.html 里. 下面实现一个利用J ...
- 使用函数库(JAVA API)
/*使用函数库(JAVA API) * 在JAVA的API里类被封装在一个个的package,要使用package的类之前必须 * 要知道这个类属于哪个package * 引用类方式: * 1.通过i ...
随机推荐
- maven学习整理-进阶知识
在maven的阶知识主要学习的是maven在eclipse中的使用.依赖相关的问题.继承(父子工程).统一版本管理.聚合等相关知识 1.maven在eclipse中的使用 由上篇基础知识学习到怎样下载 ...
- 常用内置模块(二)——logging模块
logging模块 一.logging作用 1. 控制日志级别 2. 控制日志格式 3. 控制输出的目标为文件 二.日志级别 logging.debug( logging.info( loggin ...
- Java传输对象模式
当我们想要在客户端到服务器的一个传递具有多个属性的数据时,可使用传输对象模式.传输对象也称为值对象.传输对象是一个具有getter/setter方法的简单POJO类,并且是可序列化的,因此可以通过网络 ...
- LCA的RMQ求法
参考博客 仔细想一想:最近的公共祖先,其实,搜索时回朔,连通这两点,那深度最低肯定是最近的公共祖先啊. 那这样就可以变成RMQ问题了. #include<stdio.h> #include ...
- vue-cli 利用moment.js转化时间格式为YYYY年MM月DD日,或者是YYYY-MM-DD HH:MM:SS 等格式
1.在mian.js引入moment import moment from 'moment' Vue.prototype.$moment = 'moment' 2. 在main.js 设置全局过滤器 ...
- 笔记-Linux包管理命令
一.apt, apt-get, dpkg命令 apt-get是一条linux命令,适用于deb包管理式的操作系统,主要用于自动从互联网的软件仓库中搜索.安装.升级.卸载软件或操作系统.使用apt-ge ...
- 开启SSH 使用SSH登录工具连接虚拟机
修改sshd_config文件,命令为:vi /etc/ssh/sshd_config将#PermitRootLogin without-password注释去掉修改为PermitRootLogin ...
- leetcode-263-丑数一
题目描述: 方法一:递归 class Solution: def isUgly(self, num: int) -> bool: if num == 0: return False if num ...
- IDEA中@Autowired 注解报错~图文
- LUOGU P3723 [AH2017/HNOI2017]礼物 (fft)
传送门 解题思路 首先我们设变化量为\(r\),那么最终的答案就可以写成 : \[ ans=min(\sum\limits_{i=1}^n(a_i-b_i+r)^2) \] \[ ans=min(\s ...