java中模拟http(https)请求的工具类
在java中,特别是java web中,我们经常需要碰到的一个场景是我们需要从服务端去发送http请求,获取到数据,而不是直接从浏览器输入请求网址获得相应。比如我们想访问微信接口,获取其返回信息。
在这里需要用到java的HttpURLConnection类,此类可以模拟http请求,获取到的响应以输入流的形式被程序所取到。现将相关方法整理为工具类。
- package com.m_gecko.util;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.io.OutputStreamWriter;
- import java.io.PrintWriter;
- import java.io.UnsupportedEncodingException;
- import java.net.ConnectException;
- import java.net.HttpURLConnection;
- import java.net.MalformedURLException;
- import java.net.URL;
- import java.net.URLEncoder;
- import java.util.List;
- import java.util.Map;
- import javax.net.ssl.HttpsURLConnection;
- import javax.net.ssl.SSLContext;
- import javax.net.ssl.SSLSocketFactory;
- import javax.net.ssl.TrustManager;
- import org.apache.commons.io.IOUtils;
- public class HttpUtil {
- /**
- * 模拟http的get请求,获取响应(输入流),然后把输入流转为
- *
- * @param url
- * @return
- */
- public static String httpGet(String url) {
- HttpURLConnection connection = null;
- InputStream response = null;
- try {
- connection = (HttpURLConnection) new URL(url).openConnection();
- connection.setConnectTimeout(10000);
- connection.setReadTimeout(10000);
- response = connection.getInputStream();
- if (response != null) {
- String nextLine = IOUtils.toString(response, "utf-8");
- return nextLine;
- }
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (response != null)
- try {
- response.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- if (connection != null) {
- connection.disconnect();
- connection = null;
- }
- }
- return null;
- }
- /**
- * 模拟http的post请求,类似上面
- *
- * @param url
- * @return
- */
- public static String httpPost(String url) {
- HttpURLConnection connection = null;
- InputStream response = null;
- try {
- connection = (HttpURLConnection) new URL(url).openConnection();
- connection.setConnectTimeout(30000);
- connection.setReadTimeout(30000);
- // 发送POST请求必须设置如下两行
- connection.setDoOutput(true);
- connection.setDoInput(true);
- response = connection.getInputStream();
- if (response != null) {
- String nextLine = IOUtils.toString(response, "utf-8");
- return nextLine;
- }
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (response != null)
- try {
- response.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- if (connection != null) {
- connection.disconnect();
- connection = null;
- }
- }
- return null;
- }
- /**
- * 向指定URL发送GET方法的请求
- *
- * @param url
- * 发送请求的URL
- * @param param
- * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
- * @return URL 所代表远程资源的响应结果
- */
- public static String sendGet(String url, String param) {
- String result = "";
- BufferedReader in = null;
- try {
- String urlNameString = url + "?" + param;
- URL realUrl = new URL(urlNameString);
- // 打开和URL之间的连接
- HttpURLConnection connection = (HttpURLConnection) 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.connect();
- // 获取所有响应头字段
- Map<String, List<String>> map = connection.getHeaderFields();
- // 遍历所有的响应头字段
- // for (String key : map.keySet()) {
- // System.out.println(key + "--->" + map.get(key));
- // }
- // 定义 BufferedReader输入流来读取URL的响应
- in = new BufferedReader(new InputStreamReader(
- connection.getInputStream(), "utf-8"));
- String line;
- while ((line = in.readLine()) != null) {
- result += line;
- }
- } catch (Exception e) {
- System.out.println("发送GET请求出现异常!" + e);
- e.printStackTrace();
- }
- // 使用finally块来关闭输入流
- finally {
- try {
- if (in != null) {
- in.close();
- }
- } catch (Exception e2) {
- e2.printStackTrace();
- }
- }
- return result;
- }
- /**
- * 向指定 URL 发送POST方法的请求
- *
- * @param url
- * 发送请求的 URL
- * @param param
- * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
- * @return 所代表远程资源的响应结果
- */
- public static String sendPost(String url, String param) {
- PrintWriter out = null;
- BufferedReader in = null;
- String result = "";
- try {
- URL realUrl = new URL(url);
- // 打开和URL之间的连接
- HttpURLConnection conn = (HttpURLConnection) 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);
- // 获取URLConnection对象对应的输出流
- // out = new PrintWriter(conn.getOutputStream());
- // // 发送请求参数
- // out.print(param);
- // // flush输出流的缓冲
- // out.flush();
- // 定义BufferedReader输入流来读取URL的响应
- in = new BufferedReader(new InputStreamReader(
- conn.getInputStream(), "utf-8"));
- String line;
- while ((line = in.readLine()) != null) {
- result += line;
- }
- } catch (Exception e) {
- System.out.println("发送 POST 请求出现异常!" + e);
- e.printStackTrace();
- }
- // 使用finally块来关闭输出流、输入流
- finally {
- try {
- if (out != null) {
- out.close();
- }
- if (in != null) {
- in.close();
- }
- } catch (IOException ex) {
- ex.printStackTrace();
- }
- }
- return result;
- }
- /**
- * 向指定 URL 发送POST方法的请求
- *
- * @param url
- * 发送请求的 URL
- * @param params
- * 请求的参数集合
- * @return 远程资源的响应结果
- */
- public static String sendPost(String url, Map<String, String> params) {
- OutputStreamWriter out = null;
- BufferedReader in = null;
- StringBuilder result = new StringBuilder();
- try {
- URL realUrl = new URL(url);
- HttpURLConnection conn = (HttpURLConnection) realUrl
- .openConnection();
- // 发送POST请求必须设置如下两行
- conn.setDoOutput(true);
- conn.setDoInput(true);
- // POST方法
- conn.setRequestMethod("POST");
- // 设置通用的请求属性
- conn.setRequestProperty("accept", "*/*");
- conn.setRequestProperty("connection", "Keep-Alive");
- conn.setRequestProperty("user-agent",
- "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
- conn.setRequestProperty("Content-Type",
- "application/x-www-form-urlencoded");
- conn.connect();
- // 获取URLConnection对象对应的输出流
- out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
- // 发送请求参数
- if (params != null) {
- StringBuilder param = new StringBuilder();
- for (Map.Entry<String, String> entry : params.entrySet()) {
- if (param.length() > 0) {
- param.append("&");
- }
- param.append(entry.getKey());
- param.append("=");
- param.append(entry.getValue());
- // System.out.println(entry.getKey()+":"+entry.getValue());
- }
- System.out.println("param:" + param.toString());
- out.write(param.toString());
- }
- // flush输出流的缓冲
- out.flush();
- // 定义BufferedReader输入流来读取URL的响应
- in = new BufferedReader(new InputStreamReader(
- conn.getInputStream(), "UTF-8"));
- String line;
- while ((line = in.readLine()) != null) {
- result.append(line);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- // 使用finally块来关闭输出流、输入流
- finally {
- try {
- if (out != null) {
- out.close();
- }
- if (in != null) {
- in.close();
- }
- } catch (IOException ex) {
- ex.printStackTrace();
- }
- }
- return result.toString();
- }
- /**
- * url编码
- *
- * @param str
- * @param charset
- * @return
- * @throws UnsupportedEncodingException
- */
- public static String urlEncoder(String str, String charset)
- throws UnsupportedEncodingException {
- if (str == null) {
- str = "";
- }
- String result = URLEncoder.encode(str, charset);
- return result;
- }
- /**
- * 发送https请求
- *
- * @param requestUrl
- * 请求地址
- * @param requestMethod
- * 请求方式(GET、POST)
- * @param outputStr
- * 提交的数据
- * @return 返回微信服务器响应的信息
- */
- public static String httpsRequest(String requestUrl, String requestMethod,
- String outputStr) {
- 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 conn = (HttpsURLConnection) url.openConnection();
- conn.setSSLSocketFactory(ssf);
- conn.setDoOutput(true);
- conn.setDoInput(true);
- conn.setUseCaches(false);
- // 设置请求方式(GET/POST)
- conn.setRequestMethod(requestMethod);
- conn.setRequestProperty("content-type",
- "application/x-www-form-urlencoded");
- // 当outputStr不为null时向输出流写数据
- if (null != outputStr) {
- OutputStream outputStream = conn.getOutputStream();
- // 注意编码格式
- outputStream.write(outputStr.getBytes("UTF-8"));
- outputStream.close();
- }
- // 从输入流读取返回内容
- InputStream inputStream = conn.getInputStream();
- InputStreamReader inputStreamReader = new InputStreamReader(
- inputStream, "utf-8");
- BufferedReader bufferedReader = new BufferedReader(
- inputStreamReader);
- String str = null;
- StringBuffer buffer = new StringBuffer();
- while ((str = bufferedReader.readLine()) != null) {
- buffer.append(str);
- }
- // 释放资源
- bufferedReader.close();
- inputStreamReader.close();
- inputStream.close();
- inputStream = null;
- conn.disconnect();
- return buffer.toString();
- } catch (ConnectException ce) {
- ce.printStackTrace();
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
- }
其中https请求所需要的信任管理器实现了X509TrustManager接口。
- package com.m_gecko.util;
- import java.security.cert.CertificateException;
- import java.security.cert.X509Certificate;
- import javax.net.ssl.X509TrustManager;
- /**
- * 信任管理器
- * @author xdx
- */
- public class MyX509TrustManager implements X509TrustManager {
- // 检查客户端证书
- public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
- }
- // 检查服务器端证书
- public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
- }
- // 返回受信任的X509证书数组
- public X509Certificate[] getAcceptedIssuers() {
- return null;
- }
- }
java中模拟http(https)请求的工具类的更多相关文章
- 发送http请求和https请求的工具类
package com.haiyisoft.cAssistant.utils; import java.io.IOException;import java.util.ArrayList; impor ...
- java中map和对象互转工具类的实现示例
在项目开发中,经常碰到map转实体对象或者对象转map的场景,工作中,很多时候我们可能比较喜欢使用第三方jar包的API对他们进行转化,而且用起来也还算方便,比如像fastJson就可以轻松实现map ...
- java中线程的停止以及LockSupport工具类
看jstack输出的时候,可以发现很多状态都是TIMED_WAITING(parking),如下所示: "http-bio-8080-exec-16" #70 daemon pri ...
- HTTP请求客户端工具类
1.maven 引入依赖 <dependency> <groupId>commons-httpclient</groupId> <artifactId> ...
- 模拟发送http请求的工具推荐
做网站开发时,经常需要发送请求来测试自己的代码是否OK,这时候模拟发送http请求的工具就起到了很大的作用.特别是需要在请求带header时就更加的有必要使用工具.下面推荐的工具有的是基于系统开发的程 ...
- java springboot调用第三方接口 借助hutoool工具类 爬坑
楼主是个后端小白一枚,之前没接触过后端,只学了java基本语法,还是在学校老师教的,学的很浅,什么ssh.ssm框架都没有学,最近在自学spring boot,看书学也看不是很懂,就在b站上看教学视频 ...
- java调用kettle的job和transfer工具类
package com.woaiyitiaocai.util; import java.util.Map; import java.util.UUID; import org.apache.log4j ...
- HttpUtils 用于进行网络请求的工具类
原文:http://www.open-open.com/code/view/1437537162631 import java.io.BufferedReader; import java.io.By ...
- Java Class与反射相关的一些工具类
package com.opslab.util; import org.apache.log4j.Logger; import java.io.File;import java.io.IOExcept ...
随机推荐
- eclipse中导入jsp等工程使用过程中常遇问题
1.导入的工程JSP文件出现报错的情况 这个一般不怎么影响文件的执行,这些文件飘红主要是因为eclipse的校验问题. 具体错误信息:Multiple annotations found at thi ...
- C#操作Excel知识点
近期在使用C#操作excel,主要是读取excel模板,复制其中的模板sheet页,生成多个sheet页填充相应数据后另存到excel文件,所用到的知识点如下. 一.添加引用和命名空间 添加Micro ...
- 《Linux命令行与shell脚本编程大全》 第八章管理文件系统
8.1 探索linux文件系统 8.1.1 基本的Linux文件系统 ext:最早的文件系统,叫扩展文件系统.使用虚拟目录操作硬件设备,在物理设备上按定长的块来存储数据. 用索引节点的系统来存放虚拟目 ...
- IT连创业系列:App产品上线后,运营怎么搞?(中)
等运营篇写完,计划是想写一个IOS系列,把IT连App里用到和遇到的坑都完整的和大伙分享. 不过写IOS系列前,还是要认真把这个运营篇写完,接下来好好码字!!! 上篇说到,我们计划去一次富士康门口,拉 ...
- 基于微博LBS API开发的周边美图android app
[app 不完善,就差api了] 几年之前看到过新浪微博开放API中有基于Place的API,授权后可以查看基于地理位置的一些数据,比如某个地点周边的微博动态.某个具体用户的位置动态等等.最近空余时间 ...
- js 与 ios Android交互
一.android 交互 1.js调用webview 在android API Level 17及以上的版本中,就会出现js调用不了android的代码,这是版本兼容的问题,需要在调用的方法上面加一个 ...
- PHP面向对象之const常量修饰符
在PHP中定义常量是通过define()函数来完成的,但在类中定义常量不能使用define(),而需要使用const修饰符.类中的常量使用const定义后,其访问方式和静态成员类似,都是通过类名或在成 ...
- cinder控制节点集群
#cinder控制节点集群 openstack pike 部署 目录汇总 http://www.cnblogs.com/elvi/p/7613861.html #cinder块存储控制节点.txt.s ...
- Python函数篇(3)-内置函数、文件处理
1.内置函数 上一篇文章中,我重点写了reduce.map.filter3个内置函数,在本篇章节中,会补充其他的一些常规内置函数,并重点写max,min函数,其他没有说明的函数,会在后面写到类和面向对 ...
- Wannafly挑战赛5 补题
A 珂朵莉与宇宙 题目链接: https://www.nowcoder.com/acm/contest/36/A 思路: 科学暴力:枚举前缀和,同时计算前缀和里面可能出现的完全平方数,匹配前缀和 与完 ...