在我的应用程序中,我使用以下代码下载了网站的 HTML 样式表:
private DefaultHttpClient createHttpClient() {
HttpParams my_httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(my_httpParams, 3000);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
ThreadSafeClientConnManager multiThreadedConnectionManager = new ThreadSafeClientConnManager(my_httpParams, registry);
DefaultHttpClient httpclient = new DefaultHttpClient(multiThreadedConnectionManager, my_httpParams);
return httpclient;
}
private class Example extends AsyncTask<Void, Void, Void> {
int mStatusCode = 0;
String content = "";
@Override
protected Void doInBackground(Void... args) {
String url = "www.example.com";
DefaultHttpClient httpclient = createHttpClient();
HttpGet httpget = new HttpGet(url);
try {
HttpResponse response = httpclient.execute(httpget);
StatusLine statusLine = response.getStatusLine();
mStatusCode = statusLine.getStatusCode();
if (mStatusCode == 200){
content = EntityUtils.toString(response.getEntity());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void arg) {
//Stuff
}
}
但是,有时,特别是当手机使用 3g 时,我得到 mStatusCode = 0,而其他互联网应用程序(例如浏览器)仍然可以工作。
你们知道我怎样才能防止这种情况发生吗?
非常感谢提前!