請求超時處理


package com.it;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpConnProcessThread implements Runnable {

public boolean isStop = false;

public boolean readOK = false;

private static 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;
// 讀取inputStream
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
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 void main(String[] args) throws IOException{
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();
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM