Http请求超时的一种处理方法
URLConnection类常见的超时处理就是调用其setConnectTimeout和setReadTimeout方法:
- setConnectTimeout:设置连接主机超时(单位:毫秒)
- setReadTimeout:设置从主机读取数据超时(单位:毫秒)
还有一种比较另类的就是利用java Object对象的wait()和notify()、notifyAll()方法,利用线程的等待和通知机制处理urlConnection的超时,下面直接贴代码:
public class HttpConnProcessThread implements Runnable { public boolean isStop = false; public boolean readOK = false; private HttpURLConnection reqConnection = null; public Thread readingThread; private int readLen; private String msg = null; private String reqMethod; private byte[] data; /**
* ReadThread constructor comment.
*/
public HttpConnProcessThread(HttpURLConnection reqConnection, String msg, String reqMethod ) {
super();
this.reqConnection = reqConnection;
this.msg = msg;
this.reqMethod = reqMethod;
} public void run() { InputStream input = null;
OutputStream output = null; try{
//reqConnection.connect();
output = reqConnection.getOutputStream();
if ("post".equalsIgnoreCase(reqMethod) && msg != null && msg.length() >0)
{
output.write(msg.getBytes());
output.close();
output = null;
} // 处理HTTP响应的返回状态信息
int responseCode = reqConnection.getResponseCode();// 响应的代码if( responseCode != 200 )
System.out.println("connect failed! responseCode = " + responseCode + " msg=" + reqConnection.getResponseMessage()); input = reqConnection.getInputStream(); int len;
byte[] buf = new byte[2048];
readLen = 0;
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
// 读取inputStream
while (!isStop)
{
len = input.read(buf);
if (len <= 0)
{
this.readOK = true;
input.close();
data=outStream.toByteArray();
break;
}
outStream.write(buf, 0, len);
readLen += len;
}
}
catch( IOException ie)
{}
catch(Exception e)
{}
finally
{
try{
reqConnection.disconnect();
if( input != null )
input.close();
if( output != null )
output.close(); //唤醒线程,跳出等待
wakeUp();
}catch(Exception e)
{ }
}
} public String getMessage(){
if (!readOK) //超时
{
return "";
} if (readLen <= 0) {
return "";
}
return new String(data, 0, readLen);
} public void startUp() {
this.readingThread = new Thread(this);
readingThread.start();
} //唤醒线程,不再等待
private synchronized void wakeUp() {
notifyAll();
} public synchronized void waitForData(int timeout)
{
try {
//指定超时时间,等待connection响应
wait(timeout);
}
catch (Exception e)
{
} if (!readOK)
{
isStop = true;
try{
//中断线程
if( readingThread.isAlive() )
readingThread.interrupt();
}catch(Exception e)
{ }
}
} public static main(String[] args){
String msg="";
URL reqUrl = new URL("http://127.0.0.1:8080/"); // 建立URLConnection连接
reqConnection = (HttpURLConnection) reqUrl.openConnection();
HttpConnProcessThread rec = new HttpConnProcessThread(reqConnection, msg, "post" );
rec.startUp();
// 如果顺利连接到并读完数据,则跳出等待,否则等待超时
rec.waitForData(2000); String retMessage = rec.getMessage();
}
}
Http请求超时的一种处理方法的更多相关文章
- Nodejs回调加超时限制两种实现方法
odejs回调加超时限制两种实现方法 Nodejs下的IO操作都是异步的,有时候异步请求返回太慢,不想无限等待回调怎么办呢?我们可以给回调函数加一个超时限制,到一定时间还没有回调就表示失败,继续后面的 ...
- 关于TcpClient,Socket连接超时的几种处理方法
用TcpClient做通信的时候,经常发现网络连接不通的时候,代码就卡死在那里,TcpClient竟然没有超时的设定 泪奔啊 看来微软不是把所有工具准备得妥妥当当的啊 没办法 现在用线程来包装一下这个 ...
- [Swift]Alamofire:设置网络请求超时时间【timeout】的两种方式
两种方式作用相同,是同一套代码的两种表述. 第一种方式:集聚. 直接设置成员属性(全局属性),这种方法不能灵活修改网络请求超时时间timeout. 声明为成员属性: // MARK: - 设置为全局变 ...
- [转]axios请求超时,设置重新请求的完美解决方法
自从使用Vue2之后,就使用官方推荐的axios的插件来调用API,在使用过程中,如果服务器或者网络不稳定掉包了, 你们该如何处理呢? 下面我给你们分享一下我的经历. 具体原因 最近公司在做一个项目, ...
- Django的POST请求时因为开启防止csrf,报403错误,及四种解决方法
Django默认开启防止csrf(跨站点请求伪造)攻击,在post请求时,没有上传 csrf字段,导致校验失败,报403错误 解决方法1: 注释掉此段代码,即可. 缺点:导致Django项目完全无法防 ...
- 服务器编程入门(13) Linux套接字设置超时的三种方法
摘要: 本文介绍在套接字的I/O操作上设置超时的三种方法. 图片可能有点宽,看不到的童鞋可以点击图片查看完整图片.. 1 调用alarm 使用SIGALRM为connect设置超时 设置方法: ...
- SpringMVC的请求转发的三种方法
SpringMVC请求转发的三种方法 首先明白请求转发是一次请求,地址栏不会发生变化,区别于重定向.springmvc环境自行配置. 以下举例中存在如下文件/WEB-INF/pages/success ...
- GET和POST是HTTP请求的两种基本方法,区别是什么!?
GET和POST是HTTP请求的两种基本方法,要说它们的区别,接触过WEB开发的人都能说出一二. 最直观的区别就是GET把参数包含在URL中,POST通过request body传递参数. 你可能自己 ...
- ping请求超时的解决方法
我们有时需要进行远程或者共享对方数据库的时候,会ping一下对方电脑,时候能够ping通,时候能够进行数据的传输.有时会出现ping请求超时,那么遇到这个问题该怎么解决? 我们首要解决的是看他自己是否 ...
随机推荐
- open/read/write/close
open 函数 函数原型 #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int o ...
- 集合之五:Set接口(答案)
package com.shsxt.homework; import java.util.ArrayList; import java.util.Collection; import java.uti ...
- Ubuntu16.04安装视觉SLAM环境(DBow3)
1.从Github上现在DBow3词袋模型库 git clone https://github.com/rmsalinas/DBow3.git 2.开始安装DBow3库,进入DBow3目录 mkdir ...
- 启动多个appium服务(同时运行多台设备)
准备: 一台真机一台模拟器(使用的是“夜神模拟器”) 先查看是否检测到设备 adb devices 由上图可看出没有检测到模拟器(夜神模拟器已开启) 可通过以下配置完成: 第一步:找到adb的 ...
- OpenCV识别技术
OpenCV识别技术# 老师:james 20181019 # 识别技术# Pycharm + Python3 + OpenCV """ 一.识别技术: 什么是OpenC ...
- Python 求“元组、列表、字典、数组和矩阵”的大小
总结: 首先 import numpy as np A = np.random.randint(1,100,size = (4,5)) >>A>>array([[56, 96, ...
- guava学习:guava集合类型-Bimap
学习guava让我惊喜的第二个接口就是:Bimap BiMap是一种特殊的映射其保持映射,同时确保没有重复的值是存在于该映射和一个值可以安全地用于获取键背面的倒数映射. 最近开发过程中,经常会有这种根 ...
- 解决SSH连接linux时长时间不操作自动断开
最近重装Linux系统,但是这次ssh连接云服务区Linux系统时,经常出现一段时间不操作,连接自动中断,表现为光标还在闪动,但是却无法操作.只好关闭终端,重新连接,很是麻烦. 为此,通过网络查找,找 ...
- c之指针与数组(2)Dynamic Data Structures: Malloc and Free--转载
http://www.howstuffworks.com/c29.htm http://computer.howstuffworks.com/c.htm Dynamic Data Structures ...
- oracle 数据库添加Java方法
create or replace and compile java source named "Bitconverter" aspublic class Bitconverter ...