关于get请求出错处理的开源代码

plugin 发布于 2015/02/07 01:31
阅读 132
收藏 1
/**
	 * get请求URL
	 * @param url
	 * @throws AppException 
	 */
	private static InputStream http_get(AppContext appContext, String url) throws AppException {	
		String cookie = getCookie(appContext);
		String userAgent = getUserAgent(appContext);
		
		HttpClient httpClient = null;
		GetMethod httpGet = null;

		String responseBody = "";
		int time = 0;
		do{
			try 
			{
				httpClient = getHttpClient();
				httpGet = getHttpGet(url, cookie, userAgent);			
				int statusCode = httpClient.executeMethod(httpGet);
				if (statusCode != HttpStatus.SC_OK) {
					throw AppException.http(statusCode);
				}
				responseBody = httpGet.getResponseBodyAsString();
				break;				
			} catch (HttpException e) {
				time++;
				if(time < RETRY_TIME) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {} 
					continue;
				}
				// 发生致命的异常,可能是协议不对或者返回的内容有问题
				e.printStackTrace();
				throw AppException.http(e);
			} catch (IOException e) {
				time++;
				if(time < RETRY_TIME) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {} 
					continue;
				}
				// 发生网络异常
				e.printStackTrace();
				throw AppException.network(e);
			} finally {
				// 释放连接
				httpGet.releaseConnection();
				httpClient = null;
			}
		}while(time < RETRY_TIME);
		
		//responseBody = responseBody.replaceAll("\\p{Cntrl}", "\r\n");
		if(responseBody.contains("result") && responseBody.contains("errorCode") && appContext.containsProperty("user.uid")){
			try {
				Result res = Result.parse(new ByteArrayInputStream(responseBody.getBytes()));	
				if(res.getErrorCode() == 0){
					appContext.Logout();
					appContext.getUnLoginHandler().sendEmptyMessage(1);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}			
		}
		return new ByteArrayInputStream(responseBody.getBytes());
	}


大家帮忙看一下,这个time应该是一个计次数的变量,只要不超过一定的次数,如果发生了错误,可以重新来。

但是我有点疑惑,就比如在catch(HttpException e)里面最后一句throw AppException.http(e);肯定是要执行的,也就说这是致命的错误,第一发生了就抛出异常了。那个计数的time不是有没有都无所谓吗。 

我感觉这个方法没有实现,出错了重复执行RETRY_TIME次的功能。



加载中
0
cyper
cyper
注意到32和43的行continue了吗? continue会中断本次循环后续代码的执行(也就是如果代码运行到continue后,将不再继续执行throw AppException.http(e);, 而是重新从do开始.,

只有当time>=RETRY_TIME, 跳过了continue, 才会执行throw AppException.http(e);, 从而跳出try
返回顶部
顶部