工具类包含两个方法: http请求、https请求

直接看代码:

package com.jtools;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL; import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager; /**
* http工具类
* @author json_wang
*/
public class HttpUtil {
/**
* 发起http请求并获取结果
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据 格式(例子:"name=name&age=age") // 正文,正文内容其实跟get的URL中 '? '后的参数字符串一致
* @return json字符串(json格式不确定 可能是JSONObject,也可能是JSONArray,这里用字符串,在controller里再转化)
*/
public static String httpRequest(String requestUrl, String requestMethod, String outputStr) {
String resultStr = "";
StringBuffer buffer = new StringBuffer();
try {
URL url = new URL(requestUrl);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection(); httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
//HttpURLConnection是基于HTTP协议的,其底层通过socket通信实现。如果不设置超时(timeout),在网络异常的情况下,可能会导致程序僵死而不继续往下执行
httpUrlConn.setConnectTimeout(30*1000);//30s超时
httpUrlConn.setReadTimeout(10*1000);//10s超时 /*
//设置请求属性
httpUrlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpUrlConn.setRequestProperty("Charset", "UTF-8");
*/ //HttpURLConnection的connect()函数,实际上只是建立了一个与服务器的tcp连接,并没有实际发送http请求。
//get方式需要显式连接
if ("GET".equalsIgnoreCase(requestMethod)){
httpUrlConn.connect();
} //这种post方式,隐式自动连接
// 当有数据需要提交时
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
} // 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect(); resultStr = buffer.toString();
} catch (ConnectException ce) {
System.out.println("server connection timed out.");
} catch (Exception e) {
System.out.println(requestUrl+" request error:\n"+e);
}
return resultStr;
} /**
* 发起https请求并获取结果
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据 格式(例子:"name=name&age=age") // 正文,正文内容其实跟get的URL中 '? '后的参数字符串一致
* @return json字符串(json格式不确定 可能是JSONObject,也可能是JSONArray,这里用字符串,在controller里再转化)
*/
public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
String resultStr = "";
StringBuffer buffer = new StringBuffer();
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory(); URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf); httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false); // 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
//HttpURLConnection是基于HTTP协议的,其底层通过socket通信实现。如果不设置超时(timeout),在网络异常的情况下,可能会导致程序僵死而不继续往下执行
httpUrlConn.setConnectTimeout(30*1000);//30s超时
httpUrlConn.setReadTimeout(10*1000);//10s超时 /*
//设置请求属性
httpUrlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpUrlConn.setRequestProperty("Charset", "UTF-8");
*/ //HttpURLConnection的connect()函数,实际上只是建立了一个与服务器的tcp连接,并没有实际发送http请求。
//get方式需要显式连接
if ("GET".equalsIgnoreCase(requestMethod)){
httpUrlConn.connect();
} //这种post方式,隐式自动连接
// 当有数据需要提交时
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
} // 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect(); resultStr = buffer.toString();
} catch (ConnectException ce) {
System.out.println("server connection timed out.");
} catch (Exception e) {
System.out.println(requestUrl+" request error:\n"+e);
}
return resultStr;
} public static void main(String[] args) {
System.out.println(httpRequest("https://www.zhihu.com/", "GET", null));
} }

辅助类:

package com.jtools;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; import javax.net.ssl.X509TrustManager; /**
* 证书信任管理器(用于https请求)
*/
public class MyX509TrustManager implements X509TrustManager { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
} public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
} public X509Certificate[] getAcceptedIssuers() {
return null;
}
}

附:源代码:https://github.com/JsonShare/JTools

PS:Java网络连接之HttpURLConnection与HttpClient 区别及联系 http://blog.csdn.net/wszxl492719760/article/details/8522714

Java网络连接之HttpURLConnection、HttpsURLConnection的更多相关文章

  1. Java网络连接之HttpURLConnection 与 HttpClient

    HttpClient使用详解:http://blog.csdn.net/wangpeng047/article/details/19624529   注:HttpURLConnection输出流用ou ...

  2. 动车上的书摘-java网络 连接服务器

    摘要: 摘要: 原创出处: http://www.cnblogs.com/Alandre/ 泥沙砖瓦浆木匠 希望转载,保留摘要,谢谢! 应该有些延迟,你会看到黑幕中弹出 来自USA的X原子的计量时间: ...

  3. Android网络连接之HttpURLConnection和HttpClient

    1.概念   HTTP 协议可能是现在 Internet 上使用得最多.最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源.在 JDK 的 java.net 包中 ...

  4. Andirod——网络连接(HttpURLConnection)

    Android中使用HTTP协议访问网络的方法主要分为两种: 使用HttpURLConnection 使用HttpClient 本文主要内容是HttpURLConnection的使用. HttpURL ...

  5. JAVA HTTP连接(HttpURLConnection)中使用代理(Proxy)及其验证(Authentication)

    public static void main(String[] args) { // TODO Auto-generated method stub try { URL url = new URL( ...

  6. Android4种网络连接方式HttpClient、HttpURLConnection、OKHttp和Volley优缺点和性能对比

    比较的指标: 1.cpu 2.流量 3.电量 4.内存占用 5.联网时间 功能点: 1.重试机制 2.提供的扩展功能 3.易用性 4.是否https 5.是否支持reflect api,OkHttp有 ...

  7. JAVA网络编程Socket常见问题 【长连接专题】

    一. 网络程序运行过程中的常见异常及处理 第1个异常是 java.net.BindException:Address already in use: JVM_Bind. 该异常发生在服务器端进行new ...

  8. 使用java检测网络连接状况

    windows中可以通过在cmd中使用ping命令来检测网络连接状况,如下: 网络连接正常时: 网络未连接时: 在java中可以通过调用ping命令来判断网络是否连接正常: package modul ...

  9. Android访问网络,使用HttpURLConnection还是HttpClient?

    本文转自:http://blog.csdn.net/guolin_blog/article/details/12452307,感谢这位网友的分享,谢谢. 最近在研究Volley框架的源码,发现它在HT ...

随机推荐

  1. 浅析DES与AES、RSA三种典型加密算法的比较

    DES与AES的比较 自DES 算法公诸于世以来,学术界围绕它的安全性等方面进行了研究并展开了激烈的争论.在技术上,对DES的批评主要集中在以下几个方面: 1.作为分组密码,DES 的加密单位仅有64 ...

  2. 关于数据库优化1——关于count(1),count(*),和count(列名)的区别,和关于表中字段顺序的问题

    1.关于count(1),count(*),和count(列名)的区别 相信大家总是在工作中,或者是学习中对于count()的到底怎么用更快.一直有很大的疑问,有的人说count(*)更快,也有的人说 ...

  3. 解决arcgis javascript textsymbol不支持多行文本标注的问题

    首先,下载这段js文件,命名为esri.symbol.MultiLineTextSymbol.js require(["esri/layers/LabelLayer"], func ...

  4. Log4PHP 配置和使用

    Log4PHP2.3.0使用解释 1. 什么是Log4PHP Log4php它为apche组织维护项目,是Log4xx系列日志组件之一,log4j在JAVA中可算是大名鼎鼎的日志开发包.Log4PHP ...

  5. [原]浅谈vue过渡动画,简单易懂

    在vue中什么是动画 开始先啰嗦一下,动画的解释(自我理解

  6. Centos6.5 源码编译安装 Mysql5.7.11及配置

    安装环境 Linux(CentOS6.5 版).boost_1_59_0.tar.gz.mysql-5.7.11.tar.gzMySQL 5.7主要特性:    更好的性能:对于多核CPU.固态硬盘. ...

  7. 将百度坐标转换的javascript api官方示例改写成传统的回调函数形式

    改写前: 百度地图中坐标转换的JavaScript API示例官方示例如下: var points = [new BMap.Point(116.3786889372559,39.90762965106 ...

  8. php根据经纬度获取城市名

    /*php根据经纬度获取城市名*/ function get_my_addr_infos(){ $ch = curl_init(); $timeout = 5; $lat = $list['info' ...

  9. redis可视化工具redisClient

    下载连接:百度网盘 直接解压就可以用了

  10. 8.Smarty的条件判断语句的写法

    {if $newObj eq 'a'} welcome a {elseif $a eq 'b'} welcome b {else} welcome others {/if}