开发中遇到一个奇怪的问题,app 用 httpclient 取数据,相关代码:
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;
}
取数据的过程:
httpClient = getHttpClient();
httpGet = getHttpGet(url, cookie, userAgent);
int statusCode = httpClient.executeMethod(httpGet);
if (statusCode != HttpStatus.SC_OK) {
throw AppException.http(statusCode);
}
responseBody = httpGet.getResponseBodyAsString();
碰到的问题是:url 用服务器ip,而不是域名时,在android 2.3.7版本的手机中,会停滞大约20秒再取到数据,在android4.0以上版本没有问题
原因可能是走dns的过程出现的问题
处理的方式两种:
1. 测试手机获得root权限,修改hosts,自己配一个假域名,url用假域名代替ip (真正的应用还是用域名为好,很少有直连ip的应用)
1. adb remount
2、将hosts文件复制到PC:adb pull /system/etc/hosts
3、在当前目录修改PC机上文件 hosts
4、将PC机上文件复制到手机:adb push hosts /system/etc/hosts
2. 在 getHttpGet 函数中增加一行
httpGet.getParams().setVirtualHost(IP); //IP 为 url中的ip
这两种方式都可以,而且方法2简便、通用,支持2.3.7 等版本