public class HttpsUtil {
private static class TrustAnyTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
}
private static class TrustAnyHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
/**
* 向指定URL发送POST方法的请求 (Https 模式)
*
* @param url
* 发送请求的URL
* @param content
* 发送的数据
* @param charset
* 字符集
* @return 所代表远程资源的响应结果
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws IOException
*/
public static String doSslPost(String url, String content, String charset)
throws NoSuchAlgorithmException, KeyManagementException, IOException {
// content = URLEncoder.encode(content, "UTF-8");
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
URL console = new URL(url);
HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.connect();
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.write(content.getBytes(charset));
// flush输出流的缓冲
out.flush();
out.close();
InputStream is = conn.getInputStream();
if (is != null) {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
is.close();
return new String(outStream.toByteArray(), "utf-8");
}
return null;
}
/**
* 向指定URL发送GET方法的请求 (Https 模式)
*
* @param url
* 发送请求的URL
* @param param
* 发送的数据
* @param charset
* 字符集
* @return 所代表远程资源的响应结果
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws IOException
*/
public static String doSslGet(String url, String param, String charset)
throws NoSuchAlgorithmException, KeyManagementException, IOException {
InputStream is = null;
try {
param = URLEncoder.encode(param, "UTF-8");
url = url + "?" + param;
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
URL console = new URL(url);
HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("GET");
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.connect();
is = conn.getInputStream();
if (is != null) {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
try {
return new String(outStream.toByteArray(), "utf-8");
} catch (Exception e) {
throw new RuntimeException("发送GET请求出现异常.");
} finally {
is.close();
is = null;
outStream.close();
outStream = null;
}
}
} catch (Exception e) {
throw new RuntimeException("发送GET请求出现异常.");
} finally {
if (is != null)
is.close();
}
return null;
}
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String doGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
param = URLEncoder.encode(param, "UTF-8");
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
// 建立实际的连接
connection.connect();
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
throw new RuntimeException("发送GET请求出现异常.");
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null)
in.close();
} catch (Exception e2) {
}
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String doPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
param = URLEncoder.encode(param, "UTF-8");
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.connect();
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
throw new RuntimeException("发送POST请求出现异常.");
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null)
out.close();
if (in != null)
in.close();
} catch (IOException ex) {
}
}
return result;
}
public static String sendPost(String url, String urlParam)
throws KeyManagementException, NoSuchAlgorithmException, IOException {
return url.toLowerCase().startsWith("https") ? HttpsUtil.doSslPost(url, urlParam, "utf-8")
: HttpsUtil.doPost(url, urlParam);
}
public static String postHttpUrlencoded(String url, String param, Map
String result = null;
// 构造文档约定的HTTP POST方法
HttpPost httpPost = null;
if (StringUtils.isEmpty(param)) {
httpPost = new HttpPost(url);
} else {
httpPost = new HttpPost(url + "?" + param);
}
// 设置文档中约定的Content-Type为请求的header
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
RequestConfig config = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
httpPost.setConfig(config);
HttpEntity resultEntity = null;
try {
// application/x-www-form-urlencoded 必须是键值对后台才能接收到
// 将JSON字符串设置为文档中约定的Request Body
if (postMap != null && postMap.size() > 0) {
StringEntity entity = new StringEntity(buildUrlByMap(postMap), "UTF-8");
httpPost.setEntity(entity);
System.out.println("postHttpUrlencoded-entity==>"+entity);
}
HttpClient httpClient = HttpClients.createDefault();
HttpResponse response = httpClient.execute(httpPost);
resultEntity = response.getEntity();
// 获取返回值
result = EntityUtils.toString(resultEntity, "UTF-8");
System.out.println("postHttpUrlencoded-result==>"+result);
} catch (Exception e) {
ILogUtil.error(e.getMessage());
return result;
} finally {
// 资源释放
httpPost.abort();
try {
EntityUtils.consume(resultEntity);
} catch (final IOException e) {
e.printStackTrace();
}
}
return result;
}
public static String getHttp(String url, String param) {
String result = null;
HttpGet httpGet = null;
if (!StringUtils.isEmpty(param)) {
httpGet = new HttpGet(url + "?" + param);
} else {
httpGet = new HttpGet(url);
}
httpGet.setHeader("Content-Type", "text/plain;charset=utf-8");
RequestConfig config = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
httpGet.setConfig(config);
HttpEntity resultEntity = null;
try {
// 执行请求并获取返回值
HttpClient httpClient = HttpClients.createDefault();
HttpResponse response = httpClient.execute(httpGet);
resultEntity = response.getEntity();
result = EntityUtils.toString(resultEntity, "UTF-8");
} catch (Exception e) {
ILogUtil.error(e.getMessage());
return result;
} finally {
if (httpGet != null) {
httpGet.abort();
}
try {
EntityUtils.consume(resultEntity);
} catch (final IOException e) {
}
}
return result;
}
public static String getHttp(String url,String params, Map
String result = null;
HttpGet httpGet = null;
HttpEntity resultEntity = null;
try {
params = params+ "&" + buildUrlByMap(paramMap);
httpGet = new HttpGet(url +"?"+params);
httpGet.setHeader("Content-Type", "text/plain;charset=utf-8");
RequestConfig config = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
httpGet.setConfig(config);
// 执行请求并获取返回值
HttpClient httpClient = HttpClients.createDefault();
HttpResponse response = httpClient.execute(httpGet);
resultEntity = response.getEntity();
result = EntityUtils.toString(resultEntity, "UTF-8");
} catch (Exception e) {
ILogUtil.error(e.getMessage());
return result;
} finally {
if (httpGet != null) {
httpGet.abort();
}
try {
EntityUtils.consume(resultEntity);
} catch (final IOException e) {
}
}
return result;
}
public static String postHttpJson(String url, String param, Map
String result = null;
// 构造文档约定的HTTP POST方法
HttpPost httpPost = null;
if (StringUtils.isEmpty(param)) {
httpPost = new HttpPost(url);
} else {
httpPost = new HttpPost(url + "?" + param);
}
// 设置文档中约定的Content-Type为请求的header
httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
RequestConfig config = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
httpPost.setConfig(config);
HttpEntity resultEntity = null;
try {
// 将JSON字符串设置为文档中约定的Request Body
if (postMap != null && postMap.size() > 0) {
StringEntity entity = new StringEntity(JSONObject.toJSONString(postMap), "UTF-8");
entity.setContentType("text/json");
httpPost.setEntity(entity);
}
HttpClient httpClient = HttpClients.createDefault();
HttpResponse response = httpClient.execute(httpPost);
resultEntity = response.getEntity();
// 获取返回值
result = EntityUtils.toString(resultEntity, "UTF-8");
System.out.println("postHttpJson-result==>"+result);
} catch (Exception e) {
ILogUtil.error(e.getMessage());
return result;
} finally {
// 资源释放
httpPost.abort();
try {
EntityUtils.consume(resultEntity);
} catch (final IOException e) {
e.printStackTrace();
}
}
return result;
}
public static String buildUrlByMap(Map
StringBuffer sb = new StringBuffer();
if (map.size() > 0) {
for (String key : map.keySet()) {
sb.append(key + "=");
if (StringUtils.isEmpty(map.get(key))) {
sb.append("&");
} else {
Object value = map.get(key);
try {
sb.append(URLEncoder.encode(ObjectParser.toString(value),"utf-8") + "&");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
}
System.out.println("buildUrlByMap==>"+sb.toString());
return sb.toString();
}
}