Android異常詳情介紹
這種異常我遇到以下兩種情況:
1. java.lang.IllegalStateException: No wrapped connection.
2.java.lang.IllegalStateException: Adapter is detached.
原因:
1.單線程一次執(zhí)行一個請求可以正常執(zhí)行,如果使用多線程,同時執(zhí)行多個請求時就會出現(xiàn)連接超時.
2.HttpConnection沒有連接池的概念,多少次請求就會建立多少個IO,在訪問量巨大的情況下服務(wù)器的IO可能會耗盡。
3.通常是因為HttpClient訪問單一實例的不同的線程或未關(guān)閉InputStream的httpresponse。
解決方案:獲得httpclient線程安全
解決前代碼:
public HttpClient httpClient = new DefaultHttpClient(); public void postNoResult(final Context context, final String url, final Map<String, String> maps, final String show) { new Thread() { @Override public void run() { try { HttpPost post = new HttpPost(url); List<NameValuePair> params = new ArrayList<NameValuePair>(); for (String key : maps.keySet()) { params.add(new BasicNameValuePair(key, maps.get(key))); } post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpResponse response = httpClient.execute(post);//報錯位置 if (response.getStatusLine().getStatusCode() == 200) { Looper.prepare(); String r = EntityUtils.toString(response.getEntity()); ToastUtil.print_log(r); if (show != null) { ToastUtil.show(context, show); } Looper.loop();} } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }}}.start(); }解決后代碼:
public HttpClient httpClient = getThreadSafeClient();//獲得httpclient線程安全。public static DefaultHttpClient getThreadSafeClient() {//獲得httpclient線程安全的方法 DefaultHttpClient client = new DefaultHttpClient(); ClientConnectionManager mgr = client.getConnectionManager(); HttpParams params = client.getParams(); client = new DefaultHttpClient(new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()), params); return client; } public void postNoResult(final Context context, final String url, final Map<String, String> maps, final String show) { new Thread() { @Override public void run() { try { HttpPost post = new HttpPost(url); List<NameValuePair> params = new ArrayList<NameValuePair>(); for (String key : maps.keySet()) { params.add(new BasicNameValuePair(key, maps.get(key))); } post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpResponse response = httpClient.execute(post);//報錯位置 if (response.getStatusLine().getStatusCode() == 200) { Looper.prepare(); String r = EntityUtils.toString(response.getEntity()); ToastUtil.print_log(r); if (show != null) { ToastUtil.show(context, show); } Looper.loop();} } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }}}.start(); }以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點
疑難解答