Http(Java 版 HttpURLConnection)请求的相关工具类

public class HttpUtil {

    private static final int TIMEOUT_IN_MILLIONS = 5000;

    public interface CallBack {
void onRequestComplete(String requst);
} /**
* 异步的Get请求
* @param urlStr
* @param callBack
*/
public static void doGetAsyn(final String urlStr, final CallBack callBack) {
new Thread(new Runnable() { @Override
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) {
new Thread(new Runnable() {
@Override
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[1024];
while ((len = is.read()) != -1) {
baos.write(buf, 0, len);
}
baos.flush();
return baos.toString();
} else {
throw new RuntimeException(" responseCode is not 200 ... ");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (baos != null)
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
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);
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestMethod("POST");
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;
} }

最新文章

  1. MySQL Innodb数据库性能实践——热点数据性能
  2. 初识Android NDK
  3. BookBlock - 效果非常真实的书本翻页预览
  4. Stream篇
  5. 多次快速点击相同button导致重复响应的问题
  6. 【基础知识】.Net基础加强09天
  7. iOS 开发之 Xcode6 打包生成ipa给测试
  8. [转][IIS]发布网站,提示用户 'IIS APPPOOL\***' 登录失败。
  9. 让UITableViewCell的分隔线宽度等于屏幕的宽度
  10. 1052: [HAOI2007]覆盖问题 - BZOJ
  11. hihoCoder 1513 : 小Hi的烦恼 位运算好题
  12. 章节十、3-CSS Selector---用CSS Selector - ID定位元素
  13. PJSUA2开发文档--第十章 媒体质量(MEDIA QUALITY)
  14. Python标准库01正则表达式
  15. Ionic app 通知在Moto 360 Watch上显示通知(1)
  16. 监听浏览器种类,并区分safari和chrom浏览器
  17. System.Types.hpp(77): E2029 'TObject' must be a previously defined class or struct
  18. 使用JavaScript实现ajax
  19. C/C++ 宏
  20. html5引擎开发 -- 引擎消息中心和有限状态机 - 初步整理 一

热门文章

  1. Android中Parcelable与Serializable接口用法
  2. python-web 创建一个输入链接生成的网站
  3. mysql5.6.23安装 步骤
  4. postman-3http请求
  5. Educational Codeforces Round 37-G.List Of Integers题解
  6. [Python] map Method
  7. Selenium Webdriver——Table类封装
  8. GridView弹出对话框
  9. Changing the load order/delay the start of the Server service
  10. 使用openal与mpg123播放MP3,附带工程文件(转)