android开发中,常用到get请求,实现和服务器的交互。现在研究一下 开源中国android客户端的get请求。
private final static int RETRY_TIME = 3;
/**
* get请求URL
* @param url
* @throws AppException
*/
private static InputStream http_get(AppContext appContext, String url) throws AppException {
String cookie = <strong><span style="color:#ff0000;">getCookie(appContext);</span></strong>
String userAgent = <strong><span style="color:#ff0000;">getUserAgent(appContext);</span></strong>
HttpClient httpClient = null;
GetMethod httpGet = null;
String responseBody = "";
int time = 0;
do{
try
{
httpClient =<strong><span style="color:#ff0000;"> getHttpClient();</span></strong>
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();
<strong style="background-color: rgb(255, 0, 0);">appContext.getUnLoginHandler().sendEmptyMessage(1);</strong>
}
} catch (Exception e) {
e.printStackTrace();
}
}
return new ByteArrayInputStream(responseBody.getBytes());
}
private static String getCookie(AppContext appContext) {
if(appCookie == null || appCookie == "") {
appCookie = appContext.getProperty("cookie");
}
return appCookie;
}
private static String getUserAgent(AppContext appContext) {
if(appUserAgent == null || appUserAgent == "") {
StringBuilder ua = new StringBuilder("OSChina.NET");
ua.append('/'+appContext.getPackageInfo().versionName+'_'+appContext.getPackageInfo().versionCode);//App版本
ua.append("/Android");//手机系统平台
ua.append("/"+android.os.Build.VERSION.RELEASE);//手机系统版本
ua.append("/"+android.os.Build.MODEL); //手机型号
ua.append("/"+appContext.getAppId());//客户端唯一标识
appUserAgent = ua.toString();
}
return appUserAgent;
}
设置代理参数。
private static HttpClient getHttpClient() {
HttpClient httpClient = new HttpClient();
// 设置 HttpClient 接收 Cookie,用与浏览器一样的策略
httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
// 设置 默认的超时重试处理策略
httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
// 设置 连接超时时间
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(TIMEOUT_CONNECTION);
// 设置 读数据超时时间
httpClient.getHttpConnectionManager().getParams().setSoTimeout(TIMEOUT_SOCKET);
// 设置 字符集
httpClient.getParams().setContentCharset(UTF_8);
return httpClient;
}
设置请求方法
private static GetMethod getHttpGet(String url, String cookie, String userAgent) {
GetMethod httpGet = new GetMethod(url);
// 设置 请求超时时间
httpGet.getParams().setSoTimeout(TIMEOUT_SOCKET);
httpGet.setRequestHeader("Host", URLs.HOST);
httpGet.setRequestHeader("Connection","Keep-Alive");
httpGet.setRequestHeader("Cookie", cookie);
httpGet.setRequestHeader("User-Agent", userAgent);
return httpGet;
}
/**
* 用户注销
*/
public void Logout() {
ApiClient.cleanCookie();
this.cleanCookie();
this.login = false;
this.loginUid = 0;
}
以下实现 appContext.getUnLoginHandler().sendEmptyMessage(1); 没登陆··
/**
* 未登录或修改密码后的处理
*/
public Handler getUnLoginHandler() {
return this.unLoginHandler;
}
private Handler unLoginHandler = new Handler(){
public void handleMessage(Message msg) {
if(msg.what == 1){
UIHelper.ToastMessage(AppContext.this, getString(R.string.msg_login_error));
UIHelper.showLoginDialog(AppContext.this);
}
}
};