HttpsUtils
package io.renren.modules.jqr.util;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Map.Entry;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.springframework.util.StringUtils;
/**
* http、https 请求工具类
*
* @author jiaxiaoxian
*
*/
public class HttpUtils {
private static final String DEFAULT_CHARSET = "UTF-8";
private static final String _GET = "GET"; // GET
private static final String _POST = "POST";// POST
public static final int DEF_CONN_TIMEOUT = 30000;
public static final int DEF_READ_TIMEOUT = 30000;
/**
* 初始化http请求参数
*
* @param url
* @param method
* @param headers
* @return
* @throws Exception
*/
private static HttpURLConnection initHttp(String url, String method,
Map<String, String> headers) throws Exception {
URL _url = new URL(url);
HttpURLConnection http = (HttpURLConnection) _url.openConnection();
// 连接超时
http.setConnectTimeout(DEF_CONN_TIMEOUT);
// 读取超时 --服务器响应比较慢,增大时间
http.setReadTimeout(DEF_READ_TIMEOUT);
http.setUseCaches(false);
http.setRequestMethod(method);
http.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
http.setRequestProperty(
"User-Agent",
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
if (null != headers && !headers.isEmpty()) {
for (Entry<String, String> entry : headers.entrySet()) {
http.setRequestProperty(entry.getKey(), entry.getValue());
}
}
http.setDoOutput(true);
http.setDoInput(true);
http.connect();
return http;
}
/**
* 初始化http请求参数
*
* @param url
* @param method
* @return
* @throws Exception
*/
private static HttpsURLConnection initHttps(String url, String method,
Map<String, String> headers) throws Exception {
TrustManager[] tm = { new MyX509TrustManager() };
System.setProperty("https.protocols", "TLSv1");
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL _url = new URL(url);
HttpsURLConnection http = (HttpsURLConnection) _url.openConnection();
// 设置域名校验
http.setHostnameVerifier(new HttpUtils().new TrustAnyHostnameVerifier());
// 连接超时
http.setConnectTimeout(DEF_CONN_TIMEOUT);
// 读取超时 --服务器响应比较慢,增大时间
http.setReadTimeout(DEF_READ_TIMEOUT);
http.setUseCaches(false);
http.setRequestMethod(method);
http.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
http.setRequestProperty(
"User-Agent",
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
if (null != headers && !headers.isEmpty()) {
for (Entry<String, String> entry : headers.entrySet()) {
http.setRequestProperty(entry.getKey(), entry.getValue());
}
}
http.setSSLSocketFactory(ssf);
http.setDoOutput(true);
http.setDoInput(true);
http.connect();
return http;
}
/**
*
* @description 功能描述: get 请求
* @return 返回类型:
* @throws Exception
*/
public static String get(String url, Map<String, String> params,
Map<String, String> headers) throws Exception {
HttpURLConnection http = null;
if (isHttps(url)) {
http = initHttps(initParams(url, params), _GET, headers);
} else {
http = initHttp(initParams(url, params), _GET, headers);
}
InputStream in = http.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in,
DEFAULT_CHARSET));
String valueString = null;
StringBuffer bufferRes = new StringBuffer();
// 优化,不能光使用!=null做判断。有为""的情况,防止多次空循环
while (!StringUtils.isEmpty(valueString = read.readLine())) {
bufferRes.append(valueString);
}
in.close();
if (http != null) {
http.disconnect();// 关闭连接
}
return bufferRes.toString();
}
public static String get(String url) throws Exception {
return get(url, null);
}
public static String get(String url, Map<String, String> params)
throws Exception {
return get(url, params, null);
}
public static String post(String url, String params) throws Exception {
HttpURLConnection http = null;
if (isHttps(url)) {
http = initHttps(url, _POST, null);
} else {
http = initHttp(url, _POST, null);
}
OutputStream out = http.getOutputStream();
out.write(params.getBytes(DEFAULT_CHARSET));
out.flush();
out.close();
InputStream in = http.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in,
DEFAULT_CHARSET));
String valueString = null;
StringBuffer bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null) {
bufferRes.append(valueString);
}
in.close();
if (http != null) {
http.disconnect();// 关闭连接
}
return bufferRes.toString();
}
public static String post(String url, String params,Map<String, String> headers) throws Exception {
HttpURLConnection http = null;
if (isHttps(url)) {
http = initHttps(url, _POST, headers);
} else {
http = initHttp(url, _POST, headers);
}
OutputStream out = http.getOutputStream();
out.write(params.getBytes(DEFAULT_CHARSET));
out.flush();
out.close();
InputStream in = http.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in,
DEFAULT_CHARSET));
String valueString = null;
StringBuffer bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null) {
bufferRes.append(valueString);
}
in.close();
if (http != null) {
http.disconnect();// 关闭连接
}
return bufferRes.toString();
}
/**
* 功能描述: 构造请求参数
*
* @return 返回类型:
* @throws Exception
*/
public static String initParams(String url, Map<String, String> params)
throws Exception {
if (null == params || params.isEmpty()) {
return url;
}
StringBuilder sb = new StringBuilder(url);
if (url.indexOf("?") == -1) {
sb.append("?");
}
sb.append(map2Url(params));
return sb.toString();
}
/**
* map构造url
*
* @return 返回类型:
* @throws Exception
*/
public static String map2Url(Map<String, String> paramToMap)
throws Exception {
if (null == paramToMap || paramToMap.isEmpty()) {
return null;
}
StringBuffer url = new StringBuffer();
boolean isfist = true;
for (Entry<String, String> entry : paramToMap.entrySet()) {
if (isfist) {
isfist = false;
} else {
url.append("&");
}
url.append(entry.getKey()).append("=");
String value = entry.getValue();
if (!StringUtils.isEmpty(value)) {
url.append(URLEncoder.encode(value, DEFAULT_CHARSET));
}
}
return url.toString();
}
/**
* 检测是否https
*
* @param url
*/
private static boolean isHttps(String url) {
return url.startsWith("https");
}
/**
* https 域名校验
*
* @param url
* @param params
* @return
*/
public class TrustAnyHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;// 直接返回true
}
}
private static class MyX509TrustManager implements X509TrustManager {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
};
public static void main(String[] args) {
String str = "";
try {
str = get("https://www.baidu.com");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(str);
}
}
HttpsUtils的更多相关文章
- OkHttpUtils
对okhttp的封装类,okhttp见:https://github.com/square/okhttp.目前对应okhttp版本3.3.1. 用法: Android Studio compile ' ...
- okhttp 常用使用方式 封装 演示
工具介绍 使用: AndroidStudio:[compile 'com.squareup.okhttp3:okhttp:3.4.2']和[compile 'com.zhy:okhttputils:2 ...
- 超级简单的retrofit使用自签名证书进行HTTPS请求的教程
1. 前言 HTTPS越来越成为主流,谷歌从 2017 年起,Chrome 浏览器将也会把采用 HTTP 协议的网站标记为「不安全」网站:苹果从 2017 年 iOS App 将强制使用 HTTPS: ...
- HttpClient4.5 post请求xml到服务器
1.加入HttpClient4.5和junit依赖包 <dependencies> <dependency> <groupId>org.apache.httpcom ...
- okhttputils【 Android 一个改善的okHttp封装库】使用(一)
版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 本文使用的OKHttp封装库是张鸿洋(鸿神)写的,因为在项目中一直使用这个库,所以对于一些常用的请求方式都验证过,所以特此整理下. ...
- okhttputils【 Android 一个改善的okHttp封装库】使用(二)
版权声明:本文为HaiyuKing原创文章,转载请注明出处! 上一篇讲了如何在项目中导入OKHttputils库的操作,这一篇主要讲常见请求的写法. get请求 public String getPe ...
- https遇到自签名证书/信任证书
对于CA机构颁发的证书Okhttp默认支持 可以直接访问 但是对于自定义的证书就不可以了(如:https ://kyfw.12306.cn/otn/), 需要加入Trust 下面分两部分来写,一是信任 ...
- java使用代理请求https
我本来在我本机写的代码,本机电脑是可以连外网没限制,对于https和http都可以.但是放在linux服务器上后,因为VM限制了不能访问外网,而且有ssl验证所以就一直报错,要么是连不上线上请求,要么 ...
- Jmeter AbstractJavaSamplerClient 案例
1:首先到apache-jmeter-3.0\lib\ext目录下引用以下两个jar包到Java工程里面 ApacheJMeter_core.jar ApacheJMeter_java.jar 2:新 ...
随机推荐
- JAVA复习笔记02
16.interface中的成员变量默认为public static final类型,方法只能是public(默认为public) 17.内部类访问外部类成员: Outer.this.num; 18. ...
- jmeter性能测试前及测试后
压测前: 1.压力测试两种场景: 1)单场景,压测单个接口. 2)混合场景,多个接口关联压测. 2.压测时间: ...
- vSphere、 ESXi、Vcenter、vSphere Client关系
vSphere是什么? vSphere 是VMware公司发布的一整套产品包,是VMware公司推出的一套服务器虚拟化解决方案,包含VMware ESXi hypervisor,VMware vCen ...
- 时间段(今天,昨天,本周,上周,本月,上月,总)的查询,时间处理函数strtotime
需求:最近get了一个很好用的PHP关于时间的函数strtotime,因为最近有个项目涉及到很多时间段(今天,昨天,本周,上周,本月,上月,总)的查询,要根据指定时间算出它每个范围的开始时间和结束时间 ...
- java基础类型源码解析之HashMap
终于来到比较复杂的HashMap,由于内部的变量,内部类,方法都比较多,没法像ArrayList那样直接平铺开来说,因此准备从几个具体的角度来切入. 桶结构 HashMap的每个存储位置,又叫做一个桶 ...
- scrapy基础知识之 Scrapy-Redis分布式策略:
Scrapy-Redis分布式策略: 假设有四台电脑:Windows 10.Mac OS X.Ubuntu 16.04.CentOS 7.2,任意一台电脑都可以作为 Master端 或 Slaver端 ...
- Linux命令及安装
1.三大操作系统 1.Unix Solaris(SUN) IOS(Aplle移动端) Mas OS(Aplle平板,电脑端) 2.Windows XP win7 win8 win10 3.Linux ...
- Bzoj 1997 [Hnoi2010]Planar题解
1997: [Hnoi2010]Planar Time Limit: 10 Sec Memory Limit: 64 MBSubmit: 2224 Solved: 824[Submit][Stat ...
- Ui自动化测试上传文件方法都在这里了
前言 实施UI自动化测试的时候,经常会遇见上传文件的操作,那么对于上传文件你知道几种方法呢?今天我们就总结一下几种常用的上传文件的方法,并分析一下每个方法的优点和缺点以及哪种方法效率,稳定性更高 被测 ...
- 【题解】旅行-C++
Description 某趟列车的最大载客容量为V人,沿途共有n个停靠站,其中始发站为第1站,终点站为第n站.在第1站至第n-1站之 间,共有m个团队申请购票搭乘,若规定:(1)对于某个团队的购票申请 ...