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的更多相关文章

  1. OkHttpUtils

    对okhttp的封装类,okhttp见:https://github.com/square/okhttp.目前对应okhttp版本3.3.1. 用法: Android Studio compile ' ...

  2. okhttp 常用使用方式 封装 演示

    工具介绍 使用: AndroidStudio:[compile 'com.squareup.okhttp3:okhttp:3.4.2']和[compile 'com.zhy:okhttputils:2 ...

  3. 超级简单的retrofit使用自签名证书进行HTTPS请求的教程

    1. 前言 HTTPS越来越成为主流,谷歌从 2017 年起,Chrome 浏览器将也会把采用 HTTP 协议的网站标记为「不安全」网站:苹果从 2017 年 iOS App 将强制使用 HTTPS: ...

  4. HttpClient4.5 post请求xml到服务器

    1.加入HttpClient4.5和junit依赖包 <dependencies> <dependency> <groupId>org.apache.httpcom ...

  5. okhttputils【 Android 一个改善的okHttp封装库】使用(一)

    版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 本文使用的OKHttp封装库是张鸿洋(鸿神)写的,因为在项目中一直使用这个库,所以对于一些常用的请求方式都验证过,所以特此整理下. ...

  6. okhttputils【 Android 一个改善的okHttp封装库】使用(二)

    版权声明:本文为HaiyuKing原创文章,转载请注明出处! 上一篇讲了如何在项目中导入OKHttputils库的操作,这一篇主要讲常见请求的写法. get请求 public String getPe ...

  7. https遇到自签名证书/信任证书

    对于CA机构颁发的证书Okhttp默认支持 可以直接访问 但是对于自定义的证书就不可以了(如:https ://kyfw.12306.cn/otn/), 需要加入Trust 下面分两部分来写,一是信任 ...

  8. java使用代理请求https

    我本来在我本机写的代码,本机电脑是可以连外网没限制,对于https和http都可以.但是放在linux服务器上后,因为VM限制了不能访问外网,而且有ssl验证所以就一直报错,要么是连不上线上请求,要么 ...

  9. Jmeter AbstractJavaSamplerClient 案例

    1:首先到apache-jmeter-3.0\lib\ext目录下引用以下两个jar包到Java工程里面 ApacheJMeter_core.jar ApacheJMeter_java.jar 2:新 ...

随机推荐

  1. dubbo整合springboot最详细入门教程

    说明 目前互联网公司,大部分项目都是基于分布式,一个项目被拆分成几个小项目,这些小项目会分别部署在不同的计算机上面,这个叫做微服务.当一台计算机的程序需要调用另一台计算机代码的时候,就涉及远程调用.此 ...

  2. resolv.conf 的超时(timeout)与重试(attempts)机制

    /etc/resolv.conf 有两个默认的值至关重要,一个是超时的 timeout,一个是重试的 attempts,默认情况下,前者是 5s 后者是 2 次.这个估计很多工程师都不是很在意,一般情 ...

  3. Oracle基础学习笔记

    Oracle基础学习笔记 最近找到一份实习工作,有点头疼的是,有阶段性考核,这...,实际想想看,大学期间只学过数据库原理,并没有针对某一数据库管理系统而系统的学习,这正好是一个机会,于是乎用了三天时 ...

  4. 微信小程序社区爬取

    # CrawlSpider 需要使用:规则提取器 和 解析器 # 1. allow设置规则的方法:要能够限制在目标url上面, 不要跟其他的url产生相同的正则即可 # 2. 什么情况下使用follo ...

  5. linuxprobe培训第2节课笔记2019年7月6日

    使用VM虚拟机配置RHEL实验环境. 鉴于在笔记本上装过centos7,这章内容难度对我来说不是很大. 重置root管理员密码(RHCSA考题,第一题,做不出来无法进行下一步考试) e linux16 ...

  6. Akka-CQRS(16)- gRPC用JWT进行权限管理

    前面谈过gRPC的SSL/TLS安全机制,发现设置过程比较复杂:比如证书签名:需要服务端.客户端两头都设置等.想想实际上用JWT会更加便捷,而且更安全和功能强大,因为除JWT的加密签名之外还可以把私密 ...

  7. spring的jar包的下载、说明

    spring的jar包官方下载地址:完整链接:https://repo.spring.io/webapp/#/artifacts/browse/tree/General/libs-release-lo ...

  8. [NOIP2009]靶形数独 题解

    407. [NOIP2009] 靶形数独 时间限制:5 s   内存限制:128 MB [问题描述] 小城和小华都是热爱数学的好学生,最近,他们不约而同地迷上了数独游戏,好胜的他们想用数独来一比高低. ...

  9. 20131227-backgroundPosition

    background-position 用法详细介绍 语法: background-position : length || length background-position : position ...

  10. [原创]实现MongoDB数据库审计SQL语句的脚本

    功能:实现具体显示mongodb数据库表操作语句的状态和情况,使用awk和shell实现抓取和分析处理.脚本内容如下: #!/bin/bash if [ $# == 0 ];then echo &qu ...