Java网络连接之HttpURLConnection、HttpsURLConnection
工具类包含两个方法: 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的更多相关文章
- Java网络连接之HttpURLConnection 与 HttpClient
HttpClient使用详解:http://blog.csdn.net/wangpeng047/article/details/19624529 注:HttpURLConnection输出流用ou ...
- 动车上的书摘-java网络 连接服务器
摘要: 摘要: 原创出处: http://www.cnblogs.com/Alandre/ 泥沙砖瓦浆木匠 希望转载,保留摘要,谢谢! 应该有些延迟,你会看到黑幕中弹出 来自USA的X原子的计量时间: ...
- Android网络连接之HttpURLConnection和HttpClient
1.概念 HTTP 协议可能是现在 Internet 上使用得最多.最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源.在 JDK 的 java.net 包中 ...
- Andirod——网络连接(HttpURLConnection)
Android中使用HTTP协议访问网络的方法主要分为两种: 使用HttpURLConnection 使用HttpClient 本文主要内容是HttpURLConnection的使用. HttpURL ...
- JAVA HTTP连接(HttpURLConnection)中使用代理(Proxy)及其验证(Authentication)
public static void main(String[] args) { // TODO Auto-generated method stub try { URL url = new URL( ...
- Android4种网络连接方式HttpClient、HttpURLConnection、OKHttp和Volley优缺点和性能对比
比较的指标: 1.cpu 2.流量 3.电量 4.内存占用 5.联网时间 功能点: 1.重试机制 2.提供的扩展功能 3.易用性 4.是否https 5.是否支持reflect api,OkHttp有 ...
- JAVA网络编程Socket常见问题 【长连接专题】
一. 网络程序运行过程中的常见异常及处理 第1个异常是 java.net.BindException:Address already in use: JVM_Bind. 该异常发生在服务器端进行new ...
- 使用java检测网络连接状况
windows中可以通过在cmd中使用ping命令来检测网络连接状况,如下: 网络连接正常时: 网络未连接时: 在java中可以通过调用ping命令来判断网络是否连接正常: package modul ...
- Android访问网络,使用HttpURLConnection还是HttpClient?
本文转自:http://blog.csdn.net/guolin_blog/article/details/12452307,感谢这位网友的分享,谢谢. 最近在研究Volley框架的源码,发现它在HT ...
随机推荐
- C#开发移动应用系列(1.环境搭建)
前言 是时候蹭一波热度了..咳咳..我什么都没说.. 其实也是有感而发,昨天看到Jesse写的博文(是时候开始用C#快速开发移动应用了),才幡然醒悟 , 原来我们的Xamarin已经如此的成熟了... ...
- css清除浮动的八大方法
清除浮动是每一个 web前台设计师必须掌握的机能.css清除浮动大全,共8种方法. 浮动会使当前标签产生向上浮的效果,同时会影响到前后标签.父级标签的位置及 width height 属性.而且同样的 ...
- 微信JS-SDK开发 入门指南
目录 前言 1. 过程 1.1 代码 1.2 代理 1.3 下载 1.4 解压 1.5 运行 1.6 查看 2. 微信接口测试 2.1 申请测试帐号 2.1.1 测试号信息 2.1.2 接口配置信息 ...
- [BZOJ4518]征途
4518: [Sdoi2016]征途 Time Limit: 10 Sec Memory Limit: 256 MB Description Pine开始了从S地到T地的征途. 从S地到T地的路可以 ...
- Vue的报错:Uncaught TypeError: Cannot assign to read only property 'exports' of object '#<Object>'
Vue的报错:Uncaught TypeError: Cannot assign to read only property 'exports' of object '#<Object>' ...
- tcp_wrapper 总结
一. 简介 tcp_wrapper:tcp包装器, 工作于库中的. 访问控制 工具/组件 : 传输层 和 接近于应用层; 仅对使用tcp协议且在开发时调用了libwrap相关的服务程序有效. 二. 判 ...
- 【CC2530入门教程-03】CC2530的中断系统及外部中断应用
第3课 CC2530的中断系统及外部中断应用 广东职业技术学院 欧浩源 一.中断相关的基础概念 内核与外设之间的主要交互方式有两种:轮询和中断. 轮询的方式貌似公平,但实际工作效率很低,且不能及 ...
- StructureMap经典的IoC/DI容器
StructureMap是一款很老的IoC/DI容器,从2004年.NET 1.1支持至今. 一个使用例子 //创建业务接口 public interface IDispatchService { } ...
- php7 安装yar 生成docker镜像
Docker包含三个概念:(1)远程仓库即远程镜像库所有镜像的聚集地(不可进入操作).(2)本地镜像即从远程仓库拉取过来的镜像(3)运行起来的本地镜像叫做容器(分层的可操作)Docker使用:1.首先 ...
- Spring+SpringMVC+MyBatis深入学习及搭建(十五)——SpringMVC注解开发(基础篇)
转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/7065294.html 前面讲到:Spring+SpringMVC+MyBatis深入学习及搭建(十四)--S ...