//<httpclient 版本>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.5</version>
</dependency>
//工具类
package com.kidswang.mabaobang.util;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class HttpClients {
/**
* 向HTTPS地址发送POST请求
* @param reqURL 请求地址
* @param params 请求参数
* @return 响应内容
*/
@SuppressWarnings("all")
public static String sendSSLPostRequest(String reqURL,
Map<String, String> params) {
long responseLength = 0; // 响应长度
String responseContent = null; // 响应内容
HttpClient httpClient = new DefaultHttpClient(); // 创建默认的httpClient实例
// HttpClient httpClient = new HttpClient();
X509TrustManager xtm = new X509TrustManager() { // 创建TrustManager
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
try {
// TLS1.0与SSL3.0基本上没有太大的差别,可粗略理解为TLS是SSL的继承,但它们使用的是相同的SSLContext
SSLContext ctx = SSLContext.getInstance("TLS");
// 使用TrustManager来初始化该上下文,TrustManager只是被SSL的Socket
ctx.init(null, new TrustManager[] { xtm }, null);
// 创建SSLSocketFactory
SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
// httpClient.getParams().se
// 通过SchemeRegistry将SSLSocketFactory注册到我们的HttpClient
httpClient.getConnectionManager().getSchemeRegistry()
.register(new Scheme("https", 443, socketFactory));
HttpPost httpPost = new HttpPost(reqURL); // 创建HttpPost
List<NameValuePair> formParams = new ArrayList<NameValuePair>(); // 构建POST请求的表单参
for (Map.Entry<String, String> entry : params.entrySet()) {
formParams.add(new BasicNameValuePair(entry.getKey(), entry
.getValue()));
}
httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));
HttpResponse response = httpClient.execute(httpPost); // 执行POST请求
HttpEntity entity = response.getEntity(); // 获取响应实体
if (null != entity) {
responseLength = entity.getContentLength();
responseContent = EntityUtils.toString(entity, "UTF-8");
EntityUtils.consume(entity); // Consume response content
}
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown(); // 关闭连接,释放资源
return responseContent;
}
}
/**
* 发送POST请求
* @param reqURL 请求URL
* @param params post参数
* @return
* @Description:
*/
@SuppressWarnings("finally")
public static String sendPostRequest(String reqURL,
Map<String, String> params) {
long responseLength = 0; // 响应长度
String responseContent = null; // 响应内容
HttpClient httpClient = new DefaultHttpClient(); // 创建默认的httpClient实例
// HttpClient httpClient = new HttpClient();
try {
HttpPost httpPost = new HttpPost(reqURL); // 创建HttpPost
List<NameValuePair> formParams = new ArrayList<NameValuePair>(); // 构建POST请求的表单参
for (Map.Entry<String, String> entry : params.entrySet()) {
formParams.add(new BasicNameValuePair(entry.getKey(), entry
.getValue()));
}
httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));
HttpResponse response = httpClient.execute(httpPost); // 执行POST请求
HttpEntity entity = response.getEntity(); // 获取响应实体
if (null != entity) {
responseLength = entity.getContentLength();
responseContent = EntityUtils.toString(entity, "UTF-8");
EntityUtils.consume(entity); // Consume response content
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown(); // 关闭连接,释放资源
return responseContent;
}
}
/**
* 下载文件保存到本地
* @param path 文件保存位置
* @param url 文件地址
* @throws IOException
*/
public static void downloadFile(String path, String url) throws IOException {
HttpClient client = null;
try {
// 创建HttpClient对象
client = new DefaultHttpClient();
// 获得HttpGet对象
HttpGet httpGet = getHttpGet(url, null, null);
// 发送请求获得返回结果
HttpResponse response = client.execute(httpGet);
// 如果成功
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
byte[] result = EntityUtils.toByteArray(response.getEntity());
/**
InputStream sbs = new ByteArrayInputStream(result);
BufferedOutputStream bw = null;
try {
// 创建文件对象
File f = new File(path);
// 创建文件路径
if (!f.getParentFile().exists())
f.getParentFile().mkdirs();
// 写入文件
bw = new BufferedOutputStream(new FileOutputStream(path));
bw.write(result);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
**/
}
// 如果失败
else {
StringBuffer errorMsg = new StringBuffer();
errorMsg.append("httpStatus:");
errorMsg.append(response.getStatusLine().getStatusCode());
errorMsg.append(response.getStatusLine().getReasonPhrase());
errorMsg.append(", Header: ");
Header[] headers = response.getAllHeaders();
for (Header header : headers) {
errorMsg.append(header.getName());
errorMsg.append(":");
errorMsg.append(header.getValue());
}
System.out.println("HttpResonse Error:" + errorMsg);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
throw e;
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
try {
client.getConnectionManager().shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 下载文件字节码
* @param path 文件保存位置
* @param url 文件地址
* @throws IOException
*/
public static byte[] downloadFileBytes(String url){
HttpClient client = null;
byte[] byteData = null;
try {
// 创建HttpClient对象
client = new DefaultHttpClient();
// 获得HttpGet对象
HttpGet httpGet = getHttpGet(url, null, null);
// 发送请求获得返回结果
HttpResponse response = client.execute(httpGet);
// 如果成功
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
byteData = EntityUtils.toByteArray(response.getEntity());
InputStream sbs = new ByteArrayInputStream(byteData);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
client.getConnectionManager().shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
return byteData;
}
/**
* 获得HttpGet对象
* @param url 请求地址
* @param params 请求参数
* @param encode 编码方式
* @return HttpGet对象
*/
private static HttpGet getHttpGet(String url, Map<String, String> params,
String encode) {
StringBuffer buf = new StringBuffer(url);
if (params != null) {
// 地址增加?或者&
String flag = (url.indexOf('?') == -1) ? "?" : "&";
// 添加参数
for (String name : params.keySet()) {
buf.append(flag);
buf.append(name);
buf.append("=");
try {
String param = params.get(name);
if (param == null) {
param = "";
}
buf.append(URLEncoder.encode(param, encode));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
flag = "&";
}
}
HttpGet httpGet = new HttpGet(buf.toString());
return httpGet;
}
}