HttpUtils 用于进行网络请求的工具类
原文:http://www.open-open.com/code/view/1437537162631
- import java.io.BufferedReader;
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.HttpURLConnection;
- import java.net.URL;
- //Http请求的工具类
- public class HttpUtils
- {
- private static final int TIMEOUT_IN_MILLIONS = 5000;
- public interface CallBack
- {
- void onRequestComplete(String result);
- }
- /**
- * 异步的Get请求
- *
- * @param urlStr
- * @param callBack
- */
- public static void doGetAsyn(final String urlStr, final CallBack callBack)
- {
- new Thread()
- {
- public void run()
- {
- try
- {
- String result = doGet(urlStr);
- if (callBack != null)
- {
- callBack.onRequestComplete(result);
- }
- } catch (Exception e)
- {
- e.printStackTrace();
- }
- };
- }.start();
- }
- /**
- * 异步的Post请求
- * @param urlStr
- * @param params
- * @param callBack
- * @throws Exception
- */
- public static void doPostAsyn(final String urlStr, final String params,
- final CallBack callBack) throws Exception
- {
- new Thread()
- {
- public void run()
- {
- try
- {
- String result = doPost(urlStr, params);
- if (callBack != null)
- {
- callBack.onRequestComplete(result);
- }
- } catch (Exception e)
- {
- e.printStackTrace();
- }
- };
- }.start();
- }
- /**
- * Get请求,获得返回数据
- *
- * @param urlStr
- * @return
- * @throws Exception
- */
- public static String doGet(String urlStr)
- {
- URL url = null;
- HttpURLConnection conn = null;
- InputStream is = null;
- ByteArrayOutputStream baos = null;
- try
- {
- url = new URL(urlStr);
- conn = (HttpURLConnection) url.openConnection();
- conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
- conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
- conn.setRequestMethod("GET");
- conn.setRequestProperty("accept", "*/*");
- conn.setRequestProperty("connection", "Keep-Alive");
- if (conn.getResponseCode() == 200)
- {
- is = conn.getInputStream();
- baos = new ByteArrayOutputStream();
- int len = -1;
- byte[] buf = new byte[128];
- while ((len = is.read(buf)) != -1)
- {
- baos.write(buf, 0, len);
- }
- baos.flush();
- return baos.toString();
- } else
- {
- throw new RuntimeException(" responseCode is not 200 ... ");
- }
- } catch (Exception e)
- {
- e.printStackTrace();
- } finally
- {
- try
- {
- if (is != null)
- is.close();
- } catch (IOException e)
- {
- }
- try
- {
- if (baos != null)
- baos.close();
- } catch (IOException e)
- {
- }
- conn.disconnect();
- }
- return null ;
- }
- /**
- * 向指定 URL 发送POST方法的请求
- *
- * @param url
- * 发送请求的 URL
- * @param param
- * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
- * @return 所代表远程资源的响应结果
- * @throws Exception
- */
- public static String doPost(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.setRequestMethod("POST");
- conn.setRequestProperty("Content-Type",
- "application/x-www-form-urlencoded");
- conn.setRequestProperty("charset", "utf-8");
- conn.setUseCaches(false);
- // 发送POST请求必须设置如下两行
- conn.setDoOutput(true);
- conn.setDoInput(true);
- conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
- conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
- if (param != null && !param.trim().equals(""))
- {
- // 获取URLConnection对象对应的输出流
- out = new PrintWriter(conn.getOutputStream());
- // 发送请求参数
- out.print(param);
- // flush输出流的缓冲
- out.flush();
- }
- // 定义BufferedReader输入流来读取URL的响应
- in = new BufferedReader(
- new InputStreamReader(conn.getInputStream()));
- String line;
- while ((line = in.readLine()) != null)
- {
- result += 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;
- }
- }
HttpUtils 用于进行网络请求的工具类的更多相关文章
- Android OkHttp网络连接封装工具类
package com.lidong.demo.utils; import android.os.Handler; import android.os.Looper; import com.googl ...
- HTTP请求客户端工具类
1.maven 引入依赖 <dependency> <groupId>commons-httpclient</groupId> <artifactId> ...
- 发送http请求和https请求的工具类
package com.haiyisoft.cAssistant.utils; import java.io.IOException;import java.util.ArrayList; impor ...
- 分享自己配置的HttpURLConnection请求数据工具类
>>该工具类传入string类型url返回string类型获取结果import java.io.BufferedReader;import java.io.InputStream;impo ...
- 高德地图web端笔记;发送http请求的工具类
1.查询所有电子围栏 package com.skjd.util; import java.io.BufferedReader; import java.io.InputStream; import ...
- java中模拟http(https)请求的工具类
在java中,特别是java web中,我们经常需要碰到的一个场景是我们需要从服务端去发送http请求,获取到数据,而不是直接从浏览器输入请求网址获得相应.比如我们想访问微信接口,获取其返回信息. 在 ...
- bsd socket 网络通讯必备工具类
传输数据的时候都要带上包头,包头有简单的又复杂的,简单的只要能指明数据的长度就够了. 这里我写了一个工具类,可以方便地将整型的数据长度转换为长度为 4 的字节数组. 另一方面,可以方便的将长度为 4 ...
- httputil用http获取请求的工具类
package com.xiaocan.demo.util; import java.io.IOException; import java.io.InputStream; import java.u ...
- 基于AFNetWorking 3.0封装网络请求数据的类
对于使用 AFNetworking 的朋友来说,很多朋友都是直接调用 AFNetworking的 API ,这样不太好,无法做到全工程统一配置. 最好的方式就是对网络层再封装一层,全工程不允许直接使用 ...
随机推荐
- 封装addClass 、 removeClass
<script> window.onload = function() { var oDiv = document.getElementById('div1'); var oDiv2 = ...
- resnet.caffemodel
http://blog.csdn.net/baidu_24281959/article/details/53203757
- C-基础:C语言为什么不做数组下标越界检查
//这段代码运行有可能不报错.]; ;i<;i++) { a[i]=i; } 1.为了提高运行效率,不检查数组下表越界,程序就可以跑得快.因为C语言并不是一个快速开发语言,它要求开发人员保证所有 ...
- 【软件构造】(转)Git详解、常用操作与版本图
版本控制与Git 转自:http://www.cnblogs.com/angeldevil/p/3238470.html 版本控制 版本控制是什么已不用在说了,就是记录我们对文件.目录或工程等的修改历 ...
- 洛谷——P1627 [CQOI2009]中位数
P1627 [CQOI2009]中位数 给出1~n的一个排列,统计该排列有多少个长度为奇数的连续子序列的中位数是b.中位数是指把所有元素从小到大排列后,位于中间的数. 中位数的题目有关统计的话,可以转 ...
- STL源码分析-iterator(迭代器)
1. GOF 迭代器设计模式 前面一篇文章有写到stl_list的实现,也实现了一下相应的iterator,但是后面觉得,实现具体容器之前有必要介绍一下iterator(迭代器) .那么迭代器是什么呢 ...
- [CF] 948A Protect Sheep
A. Protect Sheep time limit per test1 second memory limit per test256 megabytes inputstandard input ...
- 13. OPTIMIZER_TRACE
13. OPTIMIZER_TRACE OPTIMIZER_TRACE表提供由跟踪语句的优化程序跟踪功能生成的信息. 要启用跟踪,请使用optimizer_trace系统变量. 有关详细信息,请参阅M ...
- 8. EVENTS
8. EVENTS EVENTS表提供有关事件管理器事件的信息,这将在"使用事件调度程序"中讨论. EVENTS表有以下列: - EVENT_CATALOG:事件所属目录的名称.这 ...
- linux系统日志中出现大量systemd Starting Session ### of user root 解决
这种情况是正常的,不算是一个问题 https://access.redhat.com/solutions/1564823 Environment Red Hat Enterprise Linux 7 ...