原文:http://www.open-open.com/code/view/1437537162631

  1. import java.io.BufferedReader;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;
  6. import java.io.PrintWriter;
  7. import java.net.HttpURLConnection;
  8. import java.net.URL;
  9.  
  10. //Http请求的工具类
  11. public class HttpUtils
  12. {
  13.  
  14. private static final int TIMEOUT_IN_MILLIONS = 5000;
  15.  
  16. public interface CallBack
  17. {
  18. void onRequestComplete(String result);
  19. }
  20.  
  21. /**
  22. * 异步的Get请求
  23. *
  24. * @param urlStr
  25. * @param callBack
  26. */
  27. public static void doGetAsyn(final String urlStr, final CallBack callBack)
  28. {
  29. new Thread()
  30. {
  31. public void run()
  32. {
  33. try
  34. {
  35. String result = doGet(urlStr);
  36. if (callBack != null)
  37. {
  38. callBack.onRequestComplete(result);
  39. }
  40. } catch (Exception e)
  41. {
  42. e.printStackTrace();
  43. }
  44.  
  45. };
  46. }.start();
  47. }
  48.  
  49. /**
  50. * 异步的Post请求
  51. * @param urlStr
  52. * @param params
  53. * @param callBack
  54. * @throws Exception
  55. */
  56. public static void doPostAsyn(final String urlStr, final String params,
  57. final CallBack callBack) throws Exception
  58. {
  59. new Thread()
  60. {
  61. public void run()
  62. {
  63. try
  64. {
  65. String result = doPost(urlStr, params);
  66. if (callBack != null)
  67. {
  68. callBack.onRequestComplete(result);
  69. }
  70. } catch (Exception e)
  71. {
  72. e.printStackTrace();
  73. }
  74.  
  75. };
  76. }.start();
  77.  
  78. }
  79.  
  80. /**
  81. * Get请求,获得返回数据
  82. *
  83. * @param urlStr
  84. * @return
  85. * @throws Exception
  86. */
  87. public static String doGet(String urlStr)
  88. {
  89. URL url = null;
  90. HttpURLConnection conn = null;
  91. InputStream is = null;
  92. ByteArrayOutputStream baos = null;
  93. try
  94. {
  95. url = new URL(urlStr);
  96. conn = (HttpURLConnection) url.openConnection();
  97. conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
  98. conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
  99. conn.setRequestMethod("GET");
  100. conn.setRequestProperty("accept", "*/*");
  101. conn.setRequestProperty("connection", "Keep-Alive");
  102. if (conn.getResponseCode() == 200)
  103. {
  104. is = conn.getInputStream();
  105. baos = new ByteArrayOutputStream();
  106. int len = -1;
  107. byte[] buf = new byte[128];
  108.  
  109. while ((len = is.read(buf)) != -1)
  110. {
  111. baos.write(buf, 0, len);
  112. }
  113. baos.flush();
  114. return baos.toString();
  115. } else
  116. {
  117. throw new RuntimeException(" responseCode is not 200 ... ");
  118. }
  119.  
  120. } catch (Exception e)
  121. {
  122. e.printStackTrace();
  123. } finally
  124. {
  125. try
  126. {
  127. if (is != null)
  128. is.close();
  129. } catch (IOException e)
  130. {
  131. }
  132. try
  133. {
  134. if (baos != null)
  135. baos.close();
  136. } catch (IOException e)
  137. {
  138. }
  139. conn.disconnect();
  140. }
  141.  
  142. return null ;
  143.  
  144. }
  145.  
  146. /**
  147. * 向指定 URL 发送POST方法的请求
  148. *
  149. * @param url
  150. * 发送请求的 URL
  151. * @param param
  152. * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  153. * @return 所代表远程资源的响应结果
  154. * @throws Exception
  155. */
  156. public static String doPost(String url, String param)
  157. {
  158. PrintWriter out = null;
  159. BufferedReader in = null;
  160. String result = "";
  161. try
  162. {
  163. URL realUrl = new URL(url);
  164. // 打开和URL之间的连接
  165. HttpURLConnection conn = (HttpURLConnection) realUrl
  166. .openConnection();
  167. // 设置通用的请求属性
  168. conn.setRequestProperty("accept", "*/*");
  169. conn.setRequestProperty("connection", "Keep-Alive");
  170. conn.setRequestMethod("POST");
  171. conn.setRequestProperty("Content-Type",
  172. "application/x-www-form-urlencoded");
  173. conn.setRequestProperty("charset", "utf-8");
  174. conn.setUseCaches(false);
  175. // 发送POST请求必须设置如下两行
  176. conn.setDoOutput(true);
  177. conn.setDoInput(true);
  178. conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
  179. conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
  180.  
  181. if (param != null && !param.trim().equals(""))
  182. {
  183. // 获取URLConnection对象对应的输出流
  184. out = new PrintWriter(conn.getOutputStream());
  185. // 发送请求参数
  186. out.print(param);
  187. // flush输出流的缓冲
  188. out.flush();
  189. }
  190. // 定义BufferedReader输入流来读取URL的响应
  191. in = new BufferedReader(
  192. new InputStreamReader(conn.getInputStream()));
  193. String line;
  194. while ((line = in.readLine()) != null)
  195. {
  196. result += line;
  197. }
  198. } catch (Exception e)
  199. {
  200. e.printStackTrace();
  201. }
  202. // 使用finally块来关闭输出流、输入流
  203. finally
  204. {
  205. try
  206. {
  207. if (out != null)
  208. {
  209. out.close();
  210. }
  211. if (in != null)
  212. {
  213. in.close();
  214. }
  215. } catch (IOException ex)
  216. {
  217. ex.printStackTrace();
  218. }
  219. }
  220. return result;
  221. }
  222. }

HttpUtils 用于进行网络请求的工具类的更多相关文章

  1. Android OkHttp网络连接封装工具类

    package com.lidong.demo.utils; import android.os.Handler; import android.os.Looper; import com.googl ...

  2. HTTP请求客户端工具类

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

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

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

  4. 分享自己配置的HttpURLConnection请求数据工具类

    >>该工具类传入string类型url返回string类型获取结果import java.io.BufferedReader;import java.io.InputStream;impo ...

  5. 高德地图web端笔记;发送http请求的工具类

    1.查询所有电子围栏 package com.skjd.util; import java.io.BufferedReader; import java.io.InputStream; import ...

  6. java中模拟http(https)请求的工具类

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

  7. bsd socket 网络通讯必备工具类

    传输数据的时候都要带上包头,包头有简单的又复杂的,简单的只要能指明数据的长度就够了. 这里我写了一个工具类,可以方便地将整型的数据长度转换为长度为 4 的字节数组. 另一方面,可以方便的将长度为 4 ...

  8. httputil用http获取请求的工具类

    package com.xiaocan.demo.util; import java.io.IOException; import java.io.InputStream; import java.u ...

  9. 基于AFNetWorking 3.0封装网络请求数据的类

    对于使用 AFNetworking 的朋友来说,很多朋友都是直接调用 AFNetworking的 API ,这样不太好,无法做到全工程统一配置. 最好的方式就是对网络层再封装一层,全工程不允许直接使用 ...

随机推荐

  1. 封装addClass 、 removeClass

    <script> window.onload = function() { var oDiv = document.getElementById('div1'); var oDiv2 = ...

  2. resnet.caffemodel

    http://blog.csdn.net/baidu_24281959/article/details/53203757

  3. C-基础:C语言为什么不做数组下标越界检查

    //这段代码运行有可能不报错.]; ;i<;i++) { a[i]=i; } 1.为了提高运行效率,不检查数组下表越界,程序就可以跑得快.因为C语言并不是一个快速开发语言,它要求开发人员保证所有 ...

  4. 【软件构造】(转)Git详解、常用操作与版本图

    版本控制与Git 转自:http://www.cnblogs.com/angeldevil/p/3238470.html 版本控制 版本控制是什么已不用在说了,就是记录我们对文件.目录或工程等的修改历 ...

  5. 洛谷——P1627 [CQOI2009]中位数

    P1627 [CQOI2009]中位数 给出1~n的一个排列,统计该排列有多少个长度为奇数的连续子序列的中位数是b.中位数是指把所有元素从小到大排列后,位于中间的数. 中位数的题目有关统计的话,可以转 ...

  6. STL源码分析-iterator(迭代器)

    1. GOF 迭代器设计模式 前面一篇文章有写到stl_list的实现,也实现了一下相应的iterator,但是后面觉得,实现具体容器之前有必要介绍一下iterator(迭代器) .那么迭代器是什么呢 ...

  7. [CF] 948A Protect Sheep

    A. Protect Sheep time limit per test1 second memory limit per test256 megabytes inputstandard input ...

  8. 13. OPTIMIZER_TRACE

    13. OPTIMIZER_TRACE OPTIMIZER_TRACE表提供由跟踪语句的优化程序跟踪功能生成的信息. 要启用跟踪,请使用optimizer_trace系统变量. 有关详细信息,请参阅M ...

  9. 8. EVENTS

    8. EVENTS EVENTS表提供有关事件管理器事件的信息,这将在"使用事件调度程序"中讨论. EVENTS表有以下列: - EVENT_CATALOG:事件所属目录的名称.这 ...

  10. linux系统日志中出现大量systemd Starting Session ### of user root 解决

    这种情况是正常的,不算是一个问题 https://access.redhat.com/solutions/1564823 Environment Red Hat Enterprise Linux 7 ...