在java中,特别是java web中,我们经常需要碰到的一个场景是我们需要从服务端去发送http请求,获取到数据,而不是直接从浏览器输入请求网址获得相应。比如我们想访问微信接口,获取其返回信息。

在这里需要用到java的HttpURLConnection类,此类可以模拟http请求,获取到的响应以输入流的形式被程序所取到。现将相关方法整理为工具类。

  1. package com.m_gecko.util;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.InputStreamReader;
  7. import java.io.OutputStream;
  8. import java.io.OutputStreamWriter;
  9. import java.io.PrintWriter;
  10. import java.io.UnsupportedEncodingException;
  11. import java.net.ConnectException;
  12. import java.net.HttpURLConnection;
  13. import java.net.MalformedURLException;
  14. import java.net.URL;
  15. import java.net.URLEncoder;
  16. import java.util.List;
  17. import java.util.Map;
  18.  
  19. import javax.net.ssl.HttpsURLConnection;
  20. import javax.net.ssl.SSLContext;
  21. import javax.net.ssl.SSLSocketFactory;
  22. import javax.net.ssl.TrustManager;
  23.  
  24. import org.apache.commons.io.IOUtils;
  25.  
  26. public class HttpUtil {
  27. /**
  28. * 模拟http的get请求,获取响应(输入流),然后把输入流转为
  29. *
  30. * @param url
  31. * @return
  32. */
  33. public static String httpGet(String url) {
  34. HttpURLConnection connection = null;
  35. InputStream response = null;
  36. try {
  37. connection = (HttpURLConnection) new URL(url).openConnection();
  38. connection.setConnectTimeout(10000);
  39. connection.setReadTimeout(10000);
  40. response = connection.getInputStream();
  41. if (response != null) {
  42. String nextLine = IOUtils.toString(response, "utf-8");
  43. return nextLine;
  44. }
  45. } catch (MalformedURLException e) {
  46. e.printStackTrace();
  47. } catch (IOException e) {
  48. e.printStackTrace();
  49. } finally {
  50. if (response != null)
  51. try {
  52. response.close();
  53. } catch (IOException e) {
  54. e.printStackTrace();
  55. }
  56. if (connection != null) {
  57. connection.disconnect();
  58. connection = null;
  59. }
  60. }
  61. return null;
  62. }
  63.  
  64. /**
  65. * 模拟http的post请求,类似上面
  66. *
  67. * @param url
  68. * @return
  69. */
  70. public static String httpPost(String url) {
  71. HttpURLConnection connection = null;
  72. InputStream response = null;
  73. try {
  74. connection = (HttpURLConnection) new URL(url).openConnection();
  75. connection.setConnectTimeout(30000);
  76. connection.setReadTimeout(30000);
  77. // 发送POST请求必须设置如下两行
  78. connection.setDoOutput(true);
  79. connection.setDoInput(true);
  80. response = connection.getInputStream();
  81. if (response != null) {
  82. String nextLine = IOUtils.toString(response, "utf-8");
  83. return nextLine;
  84. }
  85. } catch (MalformedURLException e) {
  86. e.printStackTrace();
  87. } catch (IOException e) {
  88. e.printStackTrace();
  89. } finally {
  90. if (response != null)
  91. try {
  92. response.close();
  93. } catch (IOException e) {
  94. e.printStackTrace();
  95. }
  96. if (connection != null) {
  97. connection.disconnect();
  98. connection = null;
  99. }
  100. }
  101. return null;
  102. }
  103.  
  104. /**
  105. * 向指定URL发送GET方法的请求
  106. *
  107. * @param url
  108. * 发送请求的URL
  109. * @param param
  110. * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  111. * @return URL 所代表远程资源的响应结果
  112. */
  113. public static String sendGet(String url, String param) {
  114. String result = "";
  115. BufferedReader in = null;
  116. try {
  117. String urlNameString = url + "?" + param;
  118. URL realUrl = new URL(urlNameString);
  119. // 打开和URL之间的连接
  120. HttpURLConnection connection = (HttpURLConnection) realUrl
  121. .openConnection();
  122. // 设置通用的请求属性
  123. connection.setRequestProperty("accept", "*/*");
  124. connection.setRequestProperty("connection", "Keep-Alive");
  125. connection.setRequestProperty("user-agent",
  126. "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  127. // 建立实际的连接
  128. connection.connect();
  129. // 获取所有响应头字段
  130. Map<String, List<String>> map = connection.getHeaderFields();
  131. // 遍历所有的响应头字段
  132. // for (String key : map.keySet()) {
  133. // System.out.println(key + "--->" + map.get(key));
  134. // }
  135. // 定义 BufferedReader输入流来读取URL的响应
  136. in = new BufferedReader(new InputStreamReader(
  137. connection.getInputStream(), "utf-8"));
  138. String line;
  139. while ((line = in.readLine()) != null) {
  140. result += line;
  141. }
  142. } catch (Exception e) {
  143. System.out.println("发送GET请求出现异常!" + e);
  144. e.printStackTrace();
  145. }
  146. // 使用finally块来关闭输入流
  147. finally {
  148. try {
  149. if (in != null) {
  150. in.close();
  151. }
  152. } catch (Exception e2) {
  153. e2.printStackTrace();
  154. }
  155. }
  156. return result;
  157. }
  158.  
  159. /**
  160. * 向指定 URL 发送POST方法的请求
  161. *
  162. * @param url
  163. * 发送请求的 URL
  164. * @param param
  165. * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  166. * @return 所代表远程资源的响应结果
  167. */
  168. public static String sendPost(String url, String param) {
  169. PrintWriter out = null;
  170. BufferedReader in = null;
  171. String result = "";
  172. try {
  173. URL realUrl = new URL(url);
  174. // 打开和URL之间的连接
  175. HttpURLConnection conn = (HttpURLConnection) realUrl
  176. .openConnection();
  177. // 设置通用的请求属性
  178. conn.setRequestProperty("accept", "*/*");
  179. conn.setRequestProperty("connection", "Keep-Alive");
  180. conn.setRequestProperty("user-agent",
  181. "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  182. // 发送POST请求必须设置如下两行
  183. conn.setDoOutput(true);
  184. conn.setDoInput(true);
  185. // 获取URLConnection对象对应的输出流
  186. // out = new PrintWriter(conn.getOutputStream());
  187. // // 发送请求参数
  188. // out.print(param);
  189. // // flush输出流的缓冲
  190. // out.flush();
  191. // 定义BufferedReader输入流来读取URL的响应
  192. in = new BufferedReader(new InputStreamReader(
  193. conn.getInputStream(), "utf-8"));
  194. String line;
  195. while ((line = in.readLine()) != null) {
  196. result += line;
  197. }
  198. } catch (Exception e) {
  199. System.out.println("发送 POST 请求出现异常!" + e);
  200. e.printStackTrace();
  201. }
  202. // 使用finally块来关闭输出流、输入流
  203. finally {
  204. try {
  205. if (out != null) {
  206. out.close();
  207. }
  208. if (in != null) {
  209. in.close();
  210. }
  211. } catch (IOException ex) {
  212. ex.printStackTrace();
  213. }
  214. }
  215. return result;
  216. }
  217.  
  218. /**
  219. * 向指定 URL 发送POST方法的请求
  220. *
  221. * @param url
  222. * 发送请求的 URL
  223. * @param params
  224. * 请求的参数集合
  225. * @return 远程资源的响应结果
  226. */
  227. public static String sendPost(String url, Map<String, String> params) {
  228. OutputStreamWriter out = null;
  229. BufferedReader in = null;
  230. StringBuilder result = new StringBuilder();
  231. try {
  232. URL realUrl = new URL(url);
  233. HttpURLConnection conn = (HttpURLConnection) realUrl
  234. .openConnection();
  235. // 发送POST请求必须设置如下两行
  236. conn.setDoOutput(true);
  237. conn.setDoInput(true);
  238. // POST方法
  239. conn.setRequestMethod("POST");
  240. // 设置通用的请求属性
  241. conn.setRequestProperty("accept", "*/*");
  242. conn.setRequestProperty("connection", "Keep-Alive");
  243. conn.setRequestProperty("user-agent",
  244. "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  245. conn.setRequestProperty("Content-Type",
  246. "application/x-www-form-urlencoded");
  247. conn.connect();
  248. // 获取URLConnection对象对应的输出流
  249. out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
  250. // 发送请求参数
  251. if (params != null) {
  252. StringBuilder param = new StringBuilder();
  253. for (Map.Entry<String, String> entry : params.entrySet()) {
  254. if (param.length() > 0) {
  255. param.append("&");
  256. }
  257. param.append(entry.getKey());
  258. param.append("=");
  259. param.append(entry.getValue());
  260. // System.out.println(entry.getKey()+":"+entry.getValue());
  261. }
  262. System.out.println("param:" + param.toString());
  263. out.write(param.toString());
  264. }
  265. // flush输出流的缓冲
  266. out.flush();
  267. // 定义BufferedReader输入流来读取URL的响应
  268. in = new BufferedReader(new InputStreamReader(
  269. conn.getInputStream(), "UTF-8"));
  270. String line;
  271. while ((line = in.readLine()) != null) {
  272. result.append(line);
  273. }
  274. } catch (Exception e) {
  275. e.printStackTrace();
  276. }
  277. // 使用finally块来关闭输出流、输入流
  278. finally {
  279. try {
  280. if (out != null) {
  281. out.close();
  282. }
  283. if (in != null) {
  284. in.close();
  285. }
  286. } catch (IOException ex) {
  287. ex.printStackTrace();
  288. }
  289. }
  290. return result.toString();
  291. }
  292.  
  293. /**
  294. * url编码
  295. *
  296. * @param str
  297. * @param charset
  298. * @return
  299. * @throws UnsupportedEncodingException
  300. */
  301. public static String urlEncoder(String str, String charset)
  302. throws UnsupportedEncodingException {
  303. if (str == null) {
  304. str = "";
  305. }
  306. String result = URLEncoder.encode(str, charset);
  307. return result;
  308. }
  309.  
  310. /**
  311. * 发送https请求
  312. *
  313. * @param requestUrl
  314. * 请求地址
  315. * @param requestMethod
  316. * 请求方式(GET、POST)
  317. * @param outputStr
  318. * 提交的数据
  319. * @return 返回微信服务器响应的信息
  320. */
  321. public static String httpsRequest(String requestUrl, String requestMethod,
  322. String outputStr) {
  323. try {
  324. // 创建SSLContext对象,并使用我们指定的信任管理器初始化
  325. TrustManager[] tm = { new MyX509TrustManager() };
  326. SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
  327. sslContext.init(null, tm, new java.security.SecureRandom());
  328. // 从上述SSLContext对象中得到SSLSocketFactory对象
  329. SSLSocketFactory ssf = sslContext.getSocketFactory();
  330. URL url = new URL(requestUrl);
  331. HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
  332. conn.setSSLSocketFactory(ssf);
  333. conn.setDoOutput(true);
  334. conn.setDoInput(true);
  335. conn.setUseCaches(false);
  336. // 设置请求方式(GET/POST)
  337. conn.setRequestMethod(requestMethod);
  338. conn.setRequestProperty("content-type",
  339. "application/x-www-form-urlencoded");
  340. // 当outputStr不为null时向输出流写数据
  341. if (null != outputStr) {
  342. OutputStream outputStream = conn.getOutputStream();
  343. // 注意编码格式
  344. outputStream.write(outputStr.getBytes("UTF-8"));
  345. outputStream.close();
  346. }
  347. // 从输入流读取返回内容
  348. InputStream inputStream = conn.getInputStream();
  349. InputStreamReader inputStreamReader = new InputStreamReader(
  350. inputStream, "utf-8");
  351. BufferedReader bufferedReader = new BufferedReader(
  352. inputStreamReader);
  353. String str = null;
  354. StringBuffer buffer = new StringBuffer();
  355. while ((str = bufferedReader.readLine()) != null) {
  356. buffer.append(str);
  357. }
  358. // 释放资源
  359. bufferedReader.close();
  360. inputStreamReader.close();
  361. inputStream.close();
  362. inputStream = null;
  363. conn.disconnect();
  364. return buffer.toString();
  365. } catch (ConnectException ce) {
  366. ce.printStackTrace();
  367. } catch (Exception e) {
  368. e.printStackTrace();
  369. }
  370. return null;
  371. }
  372. }

其中https请求所需要的信任管理器实现了X509TrustManager接口。

  1. package com.m_gecko.util;
  2.  
  3. import java.security.cert.CertificateException;
  4. import java.security.cert.X509Certificate;
  5. import javax.net.ssl.X509TrustManager;
  6.  
  7. /**
  8. * 信任管理器
  9. * @author xdx
  10. */
  11. public class MyX509TrustManager implements X509TrustManager {
  12.  
  13. // 检查客户端证书
  14. public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  15. }
  16.  
  17. // 检查服务器端证书
  18. public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  19. }
  20.  
  21. // 返回受信任的X509证书数组
  22. public X509Certificate[] getAcceptedIssuers() {
  23. return null;
  24. }
  25. }

java中模拟http(https)请求的工具类的更多相关文章

  1. 发送http请求和https请求的工具类

    package com.haiyisoft.cAssistant.utils; import java.io.IOException;import java.util.ArrayList; impor ...

  2. java中map和对象互转工具类的实现示例

    在项目开发中,经常碰到map转实体对象或者对象转map的场景,工作中,很多时候我们可能比较喜欢使用第三方jar包的API对他们进行转化,而且用起来也还算方便,比如像fastJson就可以轻松实现map ...

  3. java中线程的停止以及LockSupport工具类

    看jstack输出的时候,可以发现很多状态都是TIMED_WAITING(parking),如下所示: "http-bio-8080-exec-16" #70 daemon pri ...

  4. HTTP请求客户端工具类

    1.maven 引入依赖 <dependency> <groupId>commons-httpclient</groupId> <artifactId> ...

  5. 模拟发送http请求的工具推荐

    做网站开发时,经常需要发送请求来测试自己的代码是否OK,这时候模拟发送http请求的工具就起到了很大的作用.特别是需要在请求带header时就更加的有必要使用工具.下面推荐的工具有的是基于系统开发的程 ...

  6. java springboot调用第三方接口 借助hutoool工具类 爬坑

    楼主是个后端小白一枚,之前没接触过后端,只学了java基本语法,还是在学校老师教的,学的很浅,什么ssh.ssm框架都没有学,最近在自学spring boot,看书学也看不是很懂,就在b站上看教学视频 ...

  7. java调用kettle的job和transfer工具类

    package com.woaiyitiaocai.util; import java.util.Map; import java.util.UUID; import org.apache.log4j ...

  8. HttpUtils 用于进行网络请求的工具类

    原文:http://www.open-open.com/code/view/1437537162631 import java.io.BufferedReader; import java.io.By ...

  9. Java Class与反射相关的一些工具类

    package com.opslab.util; import org.apache.log4j.Logger; import java.io.File;import java.io.IOExcept ...

随机推荐

  1. eclipse中导入jsp等工程使用过程中常遇问题

    1.导入的工程JSP文件出现报错的情况 这个一般不怎么影响文件的执行,这些文件飘红主要是因为eclipse的校验问题. 具体错误信息:Multiple annotations found at thi ...

  2. C#操作Excel知识点

    近期在使用C#操作excel,主要是读取excel模板,复制其中的模板sheet页,生成多个sheet页填充相应数据后另存到excel文件,所用到的知识点如下. 一.添加引用和命名空间 添加Micro ...

  3. 《Linux命令行与shell脚本编程大全》 第八章管理文件系统

    8.1 探索linux文件系统 8.1.1 基本的Linux文件系统 ext:最早的文件系统,叫扩展文件系统.使用虚拟目录操作硬件设备,在物理设备上按定长的块来存储数据. 用索引节点的系统来存放虚拟目 ...

  4. IT连创业系列:App产品上线后,运营怎么搞?(中)

    等运营篇写完,计划是想写一个IOS系列,把IT连App里用到和遇到的坑都完整的和大伙分享. 不过写IOS系列前,还是要认真把这个运营篇写完,接下来好好码字!!! 上篇说到,我们计划去一次富士康门口,拉 ...

  5. 基于微博LBS API开发的周边美图android app

    [app 不完善,就差api了] 几年之前看到过新浪微博开放API中有基于Place的API,授权后可以查看基于地理位置的一些数据,比如某个地点周边的微博动态.某个具体用户的位置动态等等.最近空余时间 ...

  6. js 与 ios Android交互

    一.android 交互 1.js调用webview 在android API Level 17及以上的版本中,就会出现js调用不了android的代码,这是版本兼容的问题,需要在调用的方法上面加一个 ...

  7. PHP面向对象之const常量修饰符

    在PHP中定义常量是通过define()函数来完成的,但在类中定义常量不能使用define(),而需要使用const修饰符.类中的常量使用const定义后,其访问方式和静态成员类似,都是通过类名或在成 ...

  8. cinder控制节点集群

    #cinder控制节点集群 openstack pike 部署 目录汇总 http://www.cnblogs.com/elvi/p/7613861.html #cinder块存储控制节点.txt.s ...

  9. Python函数篇(3)-内置函数、文件处理

    1.内置函数 上一篇文章中,我重点写了reduce.map.filter3个内置函数,在本篇章节中,会补充其他的一些常规内置函数,并重点写max,min函数,其他没有说明的函数,会在后面写到类和面向对 ...

  10. Wannafly挑战赛5 补题

    A 珂朵莉与宇宙 题目链接: https://www.nowcoder.com/acm/contest/36/A 思路: 科学暴力:枚举前缀和,同时计算前缀和里面可能出现的完全平方数,匹配前缀和 与完 ...