HttpClient4.3.6版本以上的http和https请求写法
来源:互联网 发布:eclipse java ee 64位 编辑:程序博客网 时间:2024/06/06 12:32
import
java.io.IOException;
import
java.io.UnsupportedEncodingException;
import
java.security.cert.CertificateException;
import
java.security.cert.X509Certificate;
import
java.util.ArrayList;
import
java.util.Iterator;
import
java.util.List;
import
java.util.Map;
import
javax.net.ssl.SSLContext;
import
javax.servlet.http.HttpServletRequest;
import
org.apache.http.Consts;
import
org.apache.http.HttpEntity;
import
org.apache.http.NameValuePair;
import
org.apache.http.ParseException;
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.conn.ssl.SSLConnectionSocketFactory;
import
org.apache.http.conn.ssl.SSLContextBuilder;
import
org.apache.http.conn.ssl.TrustStrategy;
import
org.apache.http.entity.StringEntity;
import
org.apache.http.impl.client.CloseableHttpClient;
import
org.apache.http.impl.client.HttpClients;
import
org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import
org.apache.http.message.BasicHeader;
import
org.apache.http.message.BasicNameValuePair;
import
org.apache.http.util.EntityUtils;
import
org.slf4j.Logger;
import
org.slf4j.LoggerFactory;
import
com.jfinal.kit.StrKit;
public
class
HttpUtil {
private
static
final
Logger logger = LoggerFactory.getLogger(HttpUtil.
class
);
// 连接超时时间
private
static
final
int
CONNECTION_TIMEOUT =
3000
;
//3秒
// 读数据超时时间
private
static
final
int
READ_DATA_TIMEOUT =
6000
;
//6秒
private
static
PoolingHttpClientConnectionManager connManager =
null
;
private
static
CloseableHttpClient httpclient =
null
;
static
{
connManager =
new
PoolingHttpClientConnectionManager();
httpclient = HttpClients.custom().setConnectionManager(connManager).build();
}
/**
* sslClient
* @return
*/
public
static
CloseableHttpClient createSSLClient() {
try
{
SSLContext sslContext =
new
SSLContextBuilder().loadTrustMaterial(
null
,
new
TrustStrategy() {
//信任所有
@Override
public
boolean
isTrusted(X509Certificate[] chain,String authType)
throws
CertificateException {
return
true
;
}
}).build();
SSLConnectionSocketFactory sslsf =
new
SSLConnectionSocketFactory(sslContext ,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
return
HttpClients.custom().setSSLSocketFactory(sslsf).build();
}
catch
(Exception e) {
e.printStackTrace();
}
return
HttpClients.createDefault();
}
/**
* Post请求(默认超时时间)
* @param url
* @param data
* @param encoding
* @return
*/
public
static
String post(String url, Map<String, Object> data, String encoding)
throws
IOException{
return
post(url, CONNECTION_TIMEOUT, READ_DATA_TIMEOUT, data, encoding);
}
public
static
String post(String url,
int
timeout ,Map<String, Object> data, String encoding)
throws
IOException{
return
post(url, timeout, timeout, data, encoding);
}
/**
* Post请求
* @param url
* @param connectTimeout
* @param readTimeout
* @param data
* @param encoding
* @return
* @throws IOException
* @throws ParseException
*/
public
static
String post(String url,
int
connectTimeout,
int
readTimeout,Map<String, Object> data, String encoding)
throws
IOException{
HttpPost post =
new
HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(readTimeout)
.setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(connectTimeout)
.setExpectContinueEnabled(
false
).build();
post.setConfig(requestConfig);
if
(
null
!=data && !data.isEmpty()) {
List<NameValuePair> formparams =
new
ArrayList<NameValuePair>();
for
(String key : data.keySet()){
formparams.add(
new
BasicNameValuePair(key, data.get(key).toString()));
}
UrlEncodedFormEntity formEntity =
new
UrlEncodedFormEntity(formparams, encoding);
post.setEntity(formEntity);
}
CloseableHttpResponse response =
null
;
if
(url.startsWith(
"https"
)){
//https
response = createSSLClient().execute(post);
}
else
{
response = httpclient.execute(post);
}
HttpEntity entity = response.getEntity();
try
{
if
(entity !=
null
){
String str = EntityUtils.toString(entity, encoding);
return
str;
}
}
finally
{
if
(entity !=
null
){
entity.getContent().close();
}
if
(response !=
null
){
response.close();
}
}
return
null
;
}
/**
* 如果失败尝试3次
* @param url
* @param encoding
* @return
*/
public
static
String tryGet(String url, String encoding){
String resultStr =
""
;
for
(
int
i =
0
; i <
3
; i++) {
try
{
resultStr = get(url, encoding);
break
;
}
catch
(Exception e) {
logger.error(
"请求异常count:{} "
,i,e);
}
}
return
resultStr;
}
/**
* Post请求(默认超时时间)
* @param url
* @param data
* @param encoding
* @return
*/
public
static
String get(String url, String encoding)
throws
IOException {
return
get(url ,
null
, CONNECTION_TIMEOUT, READ_DATA_TIMEOUT, encoding);
}
public
static
String get(String url, Map<String, String> cookies, String encoding)
throws
IOException {
return
get(url , cookies, CONNECTION_TIMEOUT, READ_DATA_TIMEOUT, encoding);
}
public
static
String get(String url, Map<String, String> cookies,
int
timeout , String encoding)
throws
IOException {
return
get(url, cookies, timeout, timeout, encoding);
}
public
static
String get(String url,Map<String, String> cookies ,
int
connectTimeout,
int
readTimeout, String encoding)
throws
IOException {
HttpGet get =
new
HttpGet(url);
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(readTimeout)
.setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(connectTimeout)
.setExpectContinueEnabled(
false
).build();
get.setConfig(requestConfig);
if
(cookies !=
null
&& !cookies.isEmpty()){
StringBuilder buffer =
new
StringBuilder(
128
);
for
(String cookieKey : cookies.keySet()){
buffer.append(cookieKey).append(
"="
).append(cookies.get(cookieKey)).append(
"; "
);
}
// 设置cookie内容
get.setHeader(
new
BasicHeader(
"Cookie"
,buffer.toString()));
}
CloseableHttpResponse response =
null
;
if
(url.startsWith(
"https"
)){
//https
response = createSSLClient().execute(get);
}
else
{
response = httpclient.execute(get);
}
HttpEntity entity = response.getEntity();
try
{
if
(entity !=
null
){
String str = EntityUtils.toString(entity, encoding);
return
str;
}
}
finally
{
if
(entity !=
null
){
entity.getContent().close();
}
if
(response !=
null
){
response.close();
}
}
return
null
;
}
/**
* sslClient
* @return
*/
public
static
String postBody(String url, String body, String encoding,
int
connectTimeout,
int
readTimeout)
throws
IOException{
HttpPost post =
new
HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(readTimeout)
.setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(connectTimeout)
.setExpectContinueEnabled(
false
).build();
post.setConfig(requestConfig);
if
(StrKit.notBlank(body)) {
StringEntity formEntity =
new
StringEntity(body, encoding);
post.setEntity(formEntity);
}
CloseableHttpResponse response =
null
;
if
(url.startsWith(
"https"
)){
//https
response = createSSLClient().execute(post);
}
else
{
response = httpclient.execute(post);
}
HttpEntity entity = response.getEntity();
try
{
if
(entity !=
null
){
String str = EntityUtils.toString(entity, encoding);
return
str;
}
}
finally
{
if
(entity !=
null
){
entity.getContent().close();
}
if
(response !=
null
){
response.close();
}
}
return
null
;
}
/**
* map转成queryStr
* @param paramMap
* @return
* @throws UnsupportedEncodingException
*/
public
static
String mapToQueryStr(Map<String,String> paramMap) {
StringBuffer strBuff =
new
StringBuffer();
for
(String key : paramMap.keySet()) {
strBuff.append(key).append(
"="
).append(paramMap.get(key)).append(
"&"
);
}
return
strBuff.substring(
0
, strBuff.length()-
1
);
}
}
0 0
- HttpClient4.3.6版本以上的http和https请求写法
- HttpClient4.3.x请求https的解决方案
- httpclient4 发送http请求的get和post用法
- https请求和http请求的转换
- HttpClient4.3.3 https请求
- HTTP和HTTPS的请求和响应
- http 和 https 的请求区别
- httpClient4.3发送https请求
- http与https的写法
- HttpClient 之 4.x.x版本以上的发送Https请求
- HttpClient模仿登陆并维持同一session请求(HttpClient4.3.X以上版本)
- Http 和 Https 访问请求
- 发起https和http请求
- android http 和https请求
- HTTP深入浅出之http请求和15中以上的请求方式
- HTTP深入浅出之http请求和15中以上的请求方式
- haproxy 中的http请求和https请求
- java http请求和https请求
- dig archive.org 国际事件解析:用DNS欺骗获得一个 .int 域名的控制权
- Codeforces Round #367 (Div. 2) C. Hard problem
- 8.1 幽灵(no.1~no.10)
- 设计模式之责任链模式--- Pattern chain-of-responsibility
- poj 3186 Treats for the Cows (区间DP)
- HttpClient4.3.6版本以上的http和https请求写法
- Java 如何将String转化为Int
- Anaconda中spyder打不开,闪一下结束
- 程序员编程的 7 + 1 条小贴士
- Oracle round函数是什么意思?怎么运用?
- Python练习100例-34
- html5中新增的一些语义化标签
- SAX解析XML文件的简单应用
- BigDecimal处理钱