HttpURLConnection的父类URLConnection有setConnectTimeout和setReadTimeout方法,分别用于设置连接和读取超时,因为子类继承了父类的方法,所以我们也可以直接用

URL newurl = new URL(url);
HttpURLConnection httpconn = (HttpURLConnection) newurl.openConnection();
httpconn.setConnectTimeout(5000);
httpconn.setReadTimeout(30000);

后面参数为超时时间,单位毫秒。一旦达到超时时间,会抛出java.net.SocketTimeoutException异常

如果要在zendAmf中添加超时,在AMFConnection.java的方法internalConnect()中添加超时,如果出现异常 ,会抛出ClientStatusException异常

protected void internalConnect() throws IOException
{
if (proxy == null)
urlConnection = (HttpURLConnection)urlObject.openConnection();
else
urlConnection = (HttpURLConnection)urlObject.openConnection(proxy);
//在这里设置网络超时
//———————————–add by zhai
      urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(30000);

//———————————–add by zhai end
urlConnection.setDoOutput(true);
setHttpRequestHeaders();
actionContext = new ActionContext();
connected = true;
}

部分内容引用 http://www.pocketdigi.com/20110723/412.html

 

 

分割线,增加HttpGet超时机制的设置

public static String getResponse(String url)
throws ClientProtocolException, IOException {

String strResult = “”;
HttpGet httpRequest = new HttpGet(url);

httpRequest.getParams().setParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
httpRequest.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
3000);

HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpRequest);
switch (httpResponse.getStatusLine().getStatusCode()) {
case HttpStatus.SC_OK:// 返回Ok的数据
strResult = EntityUtils.toString(httpResponse.getEntity());
return strResult;

}
return strResult;
}