android 中设置HttpURLConnection 超时并判断是否超时
设置超时:
URL url1 = new URL(url);
HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(3000); //3s
conn.setReadTimeout(3000); //3s
conn.setDoOutput(true);
本来以为设置了超时程序就会自动返回,不会有异常了,经过反复调试,的确会抛出SocketTimeoutException 异常
在
out = conn.getOutputStream(); //只是一个承载post内容的东西,这里并没有发送,必须在getInputStream之前
这一句会卡主,然后就异常了,所以我们要判断是否超时,则捕捉SocketTimeoutException异常就可以
整个post请求方法代码如下:
public static String sendPostRequest(String url,
Map<String, String> params, Map<String, String> headers)
throws Exception {
StringBuilder buf = new StringBuilder();
Set<Entry<String, String>> entrys = null;
String result=null;
// 如果存在参数,则放在HTTP请求体,形如name=aaa&age=10
// if (params != null && !params.isEmpty()) {
// entrys = params.entrySet();
// for (Map.Entry<String, String> entry : entrys) {
// buf.append(entry.getKey()).append("=")
// .append(URLEncoder.encode(entry.getValue(), "UTF-8"))
// .append("&");
// }
// buf.deleteCharAt(buf.length() - 1);
// }
//将参数化为xml 格式传输,格式为:<xml><datatype><![CDATA[3]]></datatype></xml>
if (params != null && !params.isEmpty()) {
entrys = params.entrySet();
buf.append("<xml>");
for (Map.Entry<String, String> entry : entrys) {
buf.append("<").append(entry.getKey()).append("><![CDATA[")
.append(URLEncoder.encode(entry.getValue(), "UTF-8"))
.append("]]></").append(entry.getKey()).append(">");
}
buf.append("</xml>");
}
URL url1 = new URL(url);
HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(3000);
conn.setReadTimeout(3000);
conn.setDoOutput(true);
OutputStream out=null;
try {
out = conn.getOutputStream(); //只是一个承载post内容的东西,这里并没有发送,必须在getInputStream之前
out.write(buf.toString().getBytes("UTF-8"));
out.flush();
if (headers != null && !headers.isEmpty()) {
entrys = headers.entrySet();
for (Map.Entry<String, String> entry : entrys) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
} //conn.getResponseCode(); // 为了发送成功
if (conn.getResponseCode() == 200) {
// 获取响应的输入流对象
InputStream is = conn.getInputStream(); //真正的发送请求
// 创建字节输出流对象
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// 定义读取的长度
int len = 0;
// 定义缓冲区
byte buffer[] = new byte[1024];
// 按照缓冲区的大小,循环读取
while ((len = is.read(buffer)) != -1) {
// 根据读取的长度写入到os对象中
baos.write(buffer, 0, len);
}
// 释放资源
is.close();
baos.close();
// 返回字符串
result = new String(baos.toByteArray());
}
else
{
result = conn.getResponseCode()+"";
}
}
catch (SocketTimeoutException ex)
{
result = "-3";
} return result;
}
android 中设置HttpURLConnection 超时并判断是否超时的更多相关文章
- Android中设置TextView的颜色setTextColor
tv.setTextColor(Color.parseColor("#FFFFFF")); tv.setTextColor(Color.WHITE); tv.setTextColo ...
- 【转】Android中设置TextView的颜色setTextColor--代码中设置字体颜色
原文网址:http://www.cnblogs.com/myphoebe/archive/2012/01/06/2314728.html android中设置TextView的颜色有方法setText ...
- 【转】Android中设置TextView的颜色setTextColor
原文网址:http://www.cnblogs.com/myphoebe/archive/2012/01/06/2314728.html android中设置TextView的颜色有方法setText ...
- Android中使用HttpURLConnection实现GET POST JSON数据与下载图片
Android中使用HttpURLConnection实现GET POST JSON数据与下载图片 Android6.0中把Apache HTTP Client全部的包与类都标记为deprecated ...
- [转]Android中设置TextView的颜色setTextColor
[转自]http://txlong-onz.iteye.com/blog/1249609 Android中设置TextView的颜色setTextColor android中设置TextView的颜色 ...
- 在Eclipse Android中设置模拟器屏幕大小
在Eclipse Android中设置模拟器屏幕大小是本文要介绍的内容,主要是来了解并学习Eclipse Android中模拟器的设置,具体关于Eclipse Android内容的详解来看本文. 方法 ...
- Android中设置全屏的方法
在实际的应用程序开发中,我们有时需要把 Activity 设置成全屏显示,一般情况下,可以通过两种方式来设置全屏显示效果.其一,通过在代码中可以设置,其二,通过manifest配置文件来设置全屏. 其 ...
- android中设置Animation 动画效果
在 Android 中, Animation 动画效果的实现可以通过两种方式进行实现,一种是 tweened animation 渐变动画,另一种是 frame by frame animation ...
- Android中设置文字大小的定义类型
在Android中所有的组件可以设置大小,但是在设置大小的时候需要指定其单位,这些单位如下: px(pixels):像素: dip(device independent pixels):依赖于设备的像 ...
随机推荐
- [老老实实学WCF] 第七篇 会话
老老实实学WCF 第七篇 会话 通过前几篇的学习,我们已经掌握了WCF的最基本的编程模型,我们已经可以写出完整的通信了.从这篇开始我们要深入地了解这个模型的高级特性,这些特性用来保证我们的程序运行的高 ...
- 20150214—winform中使用构造函数传值
构造函数,在函数初始化时就会执行的函数方法,在创建一个类之后,系统会自动在此类中生成一个与类名相同的函数,其中只包含一句代码: InitializeComponent(); 新建一个名字相同的函数,然 ...
- UI4_UIToolBar
// // AppDelegate.m // UI4_UIToolBar // // Created by zhangxueming on 15/7/6. // Copyright (c) 2015年 ...
- WCF之消息模式
请求/响应:所有操作的默认行为,在WSDL中表现为Input/Output元素. One_Way. 在WSDL中只有Input,没有回应(Output),所以没有异常报告. 单向操作只会在发出调用的瞬 ...
- 8款超酷而实用的CSS3按钮动画
1.CSS3分享按钮动画特效 这是一款基于CSS3的社会化分享按钮,按钮非常简单,提供了分享到twitter.facebook.youtube等大型社交网站.每一个分享按钮都有个大社交网站的Logo图 ...
- 南阳理工oj88--汉诺塔(一)
题目链接.http://acm.nyist.net/JudgeOnline/problem.php?pid=88 #include <stdio.h> /* //测试一下49999和500 ...
- spring4.0源码导入
一个面试,让我知道了自己的不足,一天不进步就是倒退. spring源码导入eclipse 本人的环境 (我导入的是最新的spring 4.0 所以要用jdk1.8) 1 安装git (mac上自带了g ...
- laravel步骤 (我是新手)
1/需要一个wnmp之类的虚拟服务器 2/创建路由 php artisan make:route routes Route::group(['middleware' => ['web','a ...
- 【风马一族_C】进制转化
#include "stdio.h" #include "Math.h" #define number 50 //设置数组的长度 int num10; //十进 ...
- 10.NFS V4.2
这里只演示使用keytab,也就是客户端与服务端进行keberos进行安全验证连接(注意时间服务器要同步!如果不同步,Kerberos无法通过验证) server端:192.168.1.109 1.y ...