Http请求超时的一种处理方法

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體:   |    |    |  超大  

URLConnection类常见的超时处理就是调用其setConnectTimeout和setReadTimeout方法:

setConnectTimeout:设置连接主机超时(单位:毫秒) setReadTimeout:设置从主机读取数据超时(单位:毫秒)还有一种比较另类的就是利用javaObject对象的wait()和notify()、notifyAll()方法,利用线程的等待和通知机制处理urlConnection的超时,下面直接贴代码:

publicclassHttpConnPRocessThreadimplementsRunnable {publicbooleanisStop =false;publicbooleanreadOK =false;privateHttpURLConnection reqConnection =null;publicThread readingThread;privateintreadLen;privateString msg =null;privateString reqMethod;privatebyte[] data;/*** ReadThread constructor comment.*/publicHttpConnProcessThread(HttpURLConnection reqConnection, String msg, String reqMethod ) {super();this.reqConnection =reqConnection;this.msg =msg;this.reqMethod =reqMethod;

}publicvoidrun() {

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响应的返回状态信息intresponseCode = reqConnection.getResponseCode();//响应的代码if( responseCode != 200)

System.out.println("connect failed! responseCode = " + responseCode + " msg=" +reqConnection.getResponseMessage());

input=reqConnection.getInputStream();intlen;byte[] buf =newbyte[2048];

readLen= 0;

ByteArrayOutputStream outStream=newByteArrayOutputStream();//读取inputStreamwhile(!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)

{

}

}

}publicString getMessage(){if(!readOK)//超时{return"";

}if(readLen <= 0) {return"";

}returnnewString(data, 0, readLen);

}publicvoidstartUp() {this.readingThread =newThread(this);

readingThread.start();

}//唤醒线程,不再等待privatesynchronizedvoidwakeUp() {

notifyAll();

}publicsynchronizedvoidwaitForData(inttimeout)

{try{//指定超时时间,等待connection响应wait(timeout);

}catch(Exception e)

{

}if(!readOK)

{

isStop=true;try{//中断线程if( readingThread.isAlive() )

readingThread.interrupt();

}catch(Exception e)

{

}

}

}publicstaticmain(String[] args){

String msg="";

URL reqUrl=newURL("http://127.0.0.1:8080/");//建立URLConnection连接reqConnection =(HttpURLConnection) reqUrl.openConnection();

HttpConnProcessThread rec=newHttpConnProcessThread(reqConnection, msg, "post");

rec.startUp();

//如果顺利连接到并读完数据,则跳出等待,否则等待超时rec.waitForData(2000);

String retMessage=rec.getMessage();

}

}

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航