---
title: "httpclient请求https"
author: "xj84"
date: "2014-07-21T17:31:33Z"
tags: []
categories: ["编程语言"]
slug: "httpclient-https"
draft: false
lastmod: "2014-07-21T17:31:33Z"
id: 2094629
url: "https://xj84.iteye.com/blog/2094629"
---

测试类：

package com.ali.yunos.tvmaps.web.proxy.service.impl;

 

import java.util.HashMap;

 

import org.apache.http.HttpHost;

import org.apache.http.protocol.HttpContext;

 

import com.ali.yunos.tvmaps.common.util.HttpUtil;

 

 

public class Test {

public static void main(String\[] args) {

String url="https://ali.ugamenow.com/sng/alipay/gamePrivileges";

HashMap&lt;String,Object&gt; params=new HashMap&lt;String,Object&gt;();

params.put("userId", "5623198072904114");

try {

       HttpHost host = new HttpHost("ali.ugamenow.com", 443, "https");

       HttpContext context = HttpUtil.createBasicAuthContext("alibaba", "JhtF5d53Fdgl9d", host);

       System.out.println(HttpUtil.doHttpPost(url, params, host, context));

        } catch (Exception e) {

       // TODO Auto-generated catch block

       e.printStackTrace();

        } 

    }

}

 

HttpUtil.java:

 

 

package com.ali.yunos.tvmaps.common.util;

 

 

import java.security.cert.X509Certificate;

import java.io.IOException;

import java.nio.charset.Charset;

import java.security.SecureRandom;

import java.util.HashMap;

 

import javax.net.ssl.HttpsURLConnection;

import javax.net.ssl.SSLContext;

import javax.net.ssl.TrustManager;

 

import org.apache.commons.lang.StringUtils;

import org.apache.http.HttpEntity;

import org.apache.http.HttpHost;

import org.apache.http.HttpStatus;

import org.apache.http.auth.AuthScope;

import org.apache.http.auth.Credentials;

import org.apache.http.auth.UsernamePasswordCredentials;

import org.apache.http.client.AuthCache;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.CredentialsProvider;

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.HttpPost;

import org.apache.http.client.protocol.HttpClientContext;

import org.apache.http.conn.ssl.SSLContextBuilder;

import org.apache.http.conn.ssl.TrustStrategy;

import org.apache.http.impl.auth.BasicScheme;

import org.apache.http.impl.client.BasicAuthCache;

import org.apache.http.impl.client.BasicCredentialsProvider;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.protocol.HttpContext;

import org.apache.http.util.EntityUtils;

 

import com.ali.yunos.tvmaps.common.util.ssl.SSLHostnameVerifier;

import com.ali.yunos.tvmaps.common.util.ssl.SSLTrustManager;

 

import java.io.BufferedReader;

import java.io.File;

import java.io.InputStreamReader;

import java.security.KeyManagementException;

import java.security.KeyStoreException;

import java.security.NoSuchAlgorithmException;

import java.security.cert.CertificateException;

import java.util.ArrayList;

import java.util.List;

import java.util.Map;

 

import org.apache.commons.lang.CharEncoding;

import org.apache.http.HttpResponse;

import org.apache.http.NameValuePair;

import org.apache.http.StatusLine;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.client.methods.HttpUriRequest;

import org.apache.http.client.utils.URLEncodedUtils;

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;

import org.apache.http.entity.ContentType;

import org.apache.http.entity.mime.MultipartEntityBuilder;

import org.apache.http.entity.mime.content.FileBody;

import org.apache.http.entity.mime.content.InputStreamBody;

import org.apache.http.impl.client.HttpClientBuilder;

import org.apache.http.message.BasicNameValuePair;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.web.multipart.MultipartFile;

 

 

public class HttpUtil {

 

private static final Loggerlogger= LoggerFactory.getLogger(HttpUtil.class);

 

public static void initSSLConnection() throws Exception {

TrustManager\[] tm\_array = { new SSLTrustManager() };

SSLContext sc = SSLContext.getInstance("SSL");

sc.init(null, tm\_array, new SecureRandom());

HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

HttpsURLConnection.setDefaultHostnameVerifier(new SSLHostnameVerifier());

}

 

/\**

\* HTTP GET or POST Request

* 

\* @param url

\* @param query

\* @param headers

\* @param method

\* @param file

\* @return

\* @throws ClientProtocolException

\* @throws IOException

\*/

public static String http(String url, Map&lt;String, String&gt; params, HashMap&lt;String, String&gt; headers, String method, Object file)

       throws ClientProtocolException, IOException {

if (StringUtils.isBlank(method) || (!method.equalsIgnoreCase("get") && !method.equalsIgnoreCase("post"))) {

if (logger.isWarnEnabled())

logger.warn("method is not get or post, value is {}", method);

return "method is not get or post";

}

List&lt;NameValuePair&gt; query = new ArrayList&lt;NameValuePair&gt;();

if (params != null && !params.isEmpty()) {

for (Map.Entry&lt;String, String&gt; entry : params.entrySet()) {

if (StringUtils.isBlank(entry.getValue())) {

continue;

}

query.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));

}

}

 

HttpClientBuilder builder = HttpClientBuilder.create();

CloseableHttpClient httpClient = builder.build();

url = url + "?" + URLEncodedUtils.format(query, CharEncoding.UTF\_8);

HttpUriRequest request = new HttpGet(url);

if (method.equalsIgnoreCase("post")) {

request = new HttpPost(url);

}

if (headers != null) {

for (Map.Entry&lt;String, String&gt; entry : headers.entrySet()) {

request.addHeader(entry.getKey(), entry.getValue());

}

}

HttpResponse response = null;

if (method.equalsIgnoreCase("post")) {

HttpPost postMethod = new HttpPost();

postMethod.setURI(request.getURI());

if (file != null) {

MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();

if (file instanceof File) {

File files = (File) file;

ContentType contentType = ContentType.create("image/jpeg", CharEncoding.UTF\_8);

FileBody fileBody = new FileBody(files, contentType);

entityBuilder.addPart("file", fileBody);

} else if (file instanceof MultipartFile) {

MultipartFile files = (MultipartFile) file;

InputStreamBody inputStreamBody = new InputStreamBody(files.getInputStream(), files.getOriginalFilename());

entityBuilder.addPart("file", inputStreamBody);

} else {

if (logger.isWarnEnabled())

logger.warn("the file type is unsupport exception");

throw new RuntimeException("the file type is unsupport exception");

}

HttpEntity reqEntity = entityBuilder.build();

postMethod.setEntity(reqEntity);

}

response = httpClient.execute(postMethod);

} else {

response = httpClient.execute(request);

}

StatusLine status = response.getStatusLine();

if (status != null && status.getStatusCode() != HttpStatus.SC\_OK) {

logger.error("http request failed,statusCode is {}", (status != null) ? status.getStatusCode() : "");

throw new RuntimeException("http request failed");

}

HttpEntity entity = response.getEntity();

if (entity == null) {

return StringUtils.EMPTY;

}

ContentType contentType = ContentType.getOrDefault(entity);

Charset charset = contentType.getCharset();

BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), charset), 8 * 1024);

StringBuffer sBuffer = new StringBuffer();

String line = null;

while ((line = reader.readLine()) != null) {

sBuffer.append(line);

}

reader.close();

return sBuffer.toString();

}

 

/\**

\* do HTTP/HTTPS post

* 

\* @param url

\* @param params

\* @return

\*/

public static String doHttpPost(String url, HashMap&lt;String, Object&gt; params) {

return doHttpPost(url, params, null, null);

}

 

/\**

\* do HTTP/HTTPS post, with CredentialProvider

* 

\* @param url

\* @param params

\* @return

\*/

public static String doHttpPost(String url, HashMap&lt;String, Object&gt; params, HttpHost httpHost, HttpContext context) {

CloseableHttpClient httpClient = null;

if (StringUtils.startsWith(url, "https")) {

httpClient = getSSLHttpClient();

} else {

httpClient = getHttpClient();

}

HttpPost post = new HttpPost(url);

UrlEncodedFormEntity entity = null;

try {

entity = new UrlEncodedFormEntity(buildPairList(params), getDefaultCharset(entity));

} catch (Exception e) {

logger.error("build UrlEncodedFormEntity failed , exception is {}", e);

throw new RuntimeException("build UrlEncodedFormEntity failed , exception is", e);

}

post.setEntity(entity);

CloseableHttpResponse response = null;

try {

if (context != null) {

response = httpClient.execute(httpHost, post, context);

} else {

response = httpClient.execute(post);

}

if (response == null || response.getStatusLine() == null || response.getStatusLine().getStatusCode() != HttpStatus.SC\_OK) {

logger.error("HttpUtil do http post request failed");

throw new RuntimeException("HttpUtil do http post request failed");

}

HttpEntity httpEntity = response.getEntity();

if (httpEntity == null) {

return StringUtils.EMPTY;

}

String result = EntityUtils.toString(httpEntity, getDefaultCharset(httpEntity));

EntityUtils.consume(httpEntity);

return result;

} catch (ClientProtocolException e) {

logger.error("HttpUtil do http post occurs ClientProtocolException {}", e);

throw new RuntimeException("HttpUtil do http post occurs ClientProtocolException", e);

} catch (IOException e) {

logger.error("HttpUtil do http post occurs IOException {}", e);

throw new RuntimeException("HttpUtil do http post occurs IOException", e);

} finally {

try {

response.close();

httpClient.close();

} catch (IOException e) {

logger.error("HttpUtil close httpClient occurs IOException {}", e);

throw new RuntimeException("HttpUtil close httpClient occurs IOException", e);

}

}

}

 

/\**

\* do HTTP/HTTPS request get

* 

\* @param url

\* @param params

\* @return

\*/

public static String doHttpGet(String url, HashMap&lt;String, Object&gt; params) {

return doHttpGet(url, params, null, null);

}

 

/\**

\* do HTTP/HTTPS request get, with CredentialProvider

* 

\* @param url

\* @param params

\* @return

\*/

public static String doHttpGet(String url, HashMap&lt;String, Object&gt; params, HttpHost httpHost, HttpContext context) {

CloseableHttpClient httpClient = null;

if (StringUtils.startsWith(url, "https")) {

httpClient = getSSLHttpClient();

} else {

httpClient = getHttpClient();

}

String queryUri = URLEncodedUtils.format(buildPairList(params), getDefaultCharset(null));

url = url + "?" + queryUri;

HttpGet httpGet = new HttpGet(url);

RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setSocketTimeout(30000).build();

httpGet.setConfig(requestConfig);

CloseableHttpResponse response = null;

try {

if (context != null) {

response = httpClient.execute(httpHost, httpGet, context);

} else {

response = httpClient.execute(httpGet);

}

if (response == null || response.getStatusLine() == null || response.getStatusLine().getStatusCode() != HttpStatus.SC\_OK) {

logger.error("HttpUtil do http get request failed");

throw new RuntimeException("HttpUtil do http get request failed");

}

HttpEntity httpEntity = response.getEntity();

if (httpEntity == null) {

return StringUtils.EMPTY;

}

String result = EntityUtils.toString(httpEntity, getDefaultCharset(httpEntity));

EntityUtils.consume(httpEntity);

return result;

} catch (ClientProtocolException e) {

logger.error("HttpUtil do http get occurs ClientProtocolException {}", e);

throw new RuntimeException("HttpUtil do http get occurs ClientProtocolException", e);

} catch (IOException e) {

logger.error("HttpUtil do http get occurs IOException {}", e);

throw new RuntimeException("HttpUtil do http get occurs IOException", e);

} finally {

try {

response.close();

httpClient.close();

} catch (IOException e) {

logger.error("HttpUtil close httpClient occurs IOException {}", e);

throw new RuntimeException("HttpUtil close httpClient occurs IOException", e);

}

}

}

 

private static List&lt;BasicNameValuePair&gt; buildPairList(HashMap&lt;String, Object&gt; params) {

if (params == null || params.isEmpty()) {

return new ArrayList&lt;BasicNameValuePair&gt;();

}

List&lt;BasicNameValuePair&gt; pairList = new ArrayList&lt;BasicNameValuePair&gt;();

for (Map.Entry&lt;String, Object&gt; entry : params.entrySet()) {

if (entry == null)

continue;

pairList.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));

}

if (logger.isInfoEnabled())

logger.info("HttpUtil's name value pair size {}", pairList.size());

return pairList;

}

 

private static Charset getDefaultCharset(HttpEntity entity) {

if (entity == null)

return Charset.forName(CharEncoding.UTF\_8);

ContentType contentType = ContentType.getOrDefault(entity);

return contentType.getCharset();

}

 

private static CloseableHttpClient getHttpClient() {

RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(48000).setSocketTimeout(30000).build();

return HttpClients.custom().setDefaultRequestConfig(requestConfig).build();

}

 

private static CloseableHttpClient getSSLHttpClient() {

try {

SSLContext context = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

 

@Override

public boolean isTrusted(X509Certificate\[] chain, String authType) throws CertificateException {

return true;

}

}).build();

SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(context);

RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(48000).setSocketTimeout(30000).build();

return HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultRequestConfig(requestConfig).build();

} catch (KeyManagementException e) {

logger.error("ssl context key management Exception {}", e);

throw new RuntimeException("ssl context key management Exception", e);

} catch (NoSuchAlgorithmException e) {

logger.error("ssl context get instance faild, no such method {}", e);

throw new RuntimeException("ssl context get instance faild", e);

} catch (KeyStoreException e) {

logger.error("ssl context key store Exception {}", e);

throw new RuntimeException("ssl context key store Exception", e);

}

}

 

public static String doPost(String url, Map&lt;String, String&gt; headers, HashMap&lt;String, Object&gt; params) throws IOException {

CloseableHttpClient client = getSSLHttpClient();

HttpPost post = new HttpPost(url);

for (Map.Entry&lt;String, String&gt; header : headers.entrySet()) {

post.setHeader(header.getKey(), header.getValue());

}

UrlEncodedFormEntity entity = new UrlEncodedFormEntity(buildPairList(params), getDefaultCharset(null));

post.setEntity(entity);

HttpHost host = new HttpHost("ali.ugamenow.com", 443, "https");

HttpContext context = createBasicAuthContext("alibaba", "JhtF5d53Fdgl9d", host);

CloseableHttpResponse response = client.execute(host, post, context);

try {

if (response == null || response.getStatusLine() == null || response.getStatusLine().getStatusCode() != HttpStatus.SC\_OK) {

logger.error("HttpUtil do http get request failed");

throw new RuntimeException("HttpUtil do http get request failed");

}

HttpEntity httpEntity = response.getEntity();

if (httpEntity == null) {

return StringUtils.EMPTY;

}

String result = EntityUtils.toString(httpEntity, getDefaultCharset(httpEntity));

EntityUtils.consume(httpEntity);

response.close();

client.close();

return result;

} finally {

response.close();

}

}

 

public static HttpClientContext createBasicAuthContext(String username, String password, HttpHost host) {

CredentialsProvider credsProvider = new BasicCredentialsProvider();

Credentials defaultCreds = new UsernamePasswordCredentials(username, password);

credsProvider.setCredentials(new AuthScope(host.getHostName(), host.getPort()), defaultCreds);

 

AuthCache authCache = new BasicAuthCache();

BasicScheme basicAuth = new BasicScheme(Charset.forName("UTF-8"));

authCache.put(host, basicAuth);

 

HttpClientContext context = HttpClientContext.create();

context.setCredentialsProvider(credsProvider);

context.setAuthCache(authCache);

return context;

}

 

}

 

maven依赖：

&lt;dependency&gt;

&lt;groupId&gt;commons-httpclient&lt;/groupId&gt;

&lt;artifactId&gt;commons-httpclient&lt;/artifactId&gt;

&lt;version&gt;3.1&lt;/version&gt;

&lt;/dependency&gt;

&lt;dependency&gt;

&lt;groupId&gt;org.apache.httpcomponents&lt;/groupId&gt;

&lt;artifactId&gt;httpclient&lt;/artifactId&gt;

&lt;version&gt;4.3.4&lt;/version&gt;

&lt;/dependency&gt;

&lt;dependency&gt;

&lt;groupId&gt;org.apache.httpcomponents&lt;/groupId&gt;

&lt;artifactId&gt;httpcore&lt;/artifactId&gt;

&lt;version&gt;4.3.2&lt;/version&gt;

&lt;/dependency&gt;

&lt;dependency&gt;

&lt;groupId&gt;org.apache.httpcomponents&lt;/groupId&gt;

&lt;artifactId&gt;httpmime&lt;/artifactId&gt;

&lt;version&gt;4.3.4&lt;/version&gt;

&lt;/dependency&gt;

&lt;dependency&gt;

            &lt;groupId&gt;commons-codec&lt;/groupId&gt;

            &lt;artifactId&gt;commons-codec&lt;/artifactId&gt;

            &lt;version&gt;1.6&lt;/version&gt;

&lt;/dependency&gt;