0

我正在使用以下函数,但有 AsyncTask Exception 虽然我得到了有效的响应,为什么会这样。

public static void LoadServer(SharedPreferences prefs) {

    InputStream inputStream = null;
    String json = "";
    String urlStr = "";


    urlStr = String.format("http://mydomin/settings.php",
            prefs.getString("DomainName", ""));

    Log.v("URL", urlStr);

    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();

        // String encodeUrl = URLEncoder.encode(urlStr, "UTF-8");

        HttpGet httpGet = new HttpGet(urlStr);
        httpGet.addHeader("accept", "application/json");
        httpGet.addHeader("Host", prefs.getString("DomainName", ""));
        httpGet.addHeader("Cookie", prefs.getString("MyCookie", ""));

        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        inputStream = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                inputStream, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        inputStream.close();


        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        serverObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

}

例外情况如下:

 04-23 16:46:31.457: W/System.err(23621): [DEBUG] GbaRequest - GbaRequest: Constructor Called 222 userAgent Apache-HttpClient/UNAVAILABLE (java 1.4)
04-23 16:46:31.457: W/System.err(23621): [DEBUG] NafRequest - NafRequest: NafRequest constructor===useragent Apache-HttpClient/UNAVAILABLE (java 1.4)
04-23 16:46:31.497: I/System.out(23621): AsyncTask #1(ApacheHTTPLog):getSBService() is false
04-23 16:46:31.497: I/System.out(23621): AsyncTask #1(ApacheHTTPLog):SMARTBONDING_ENABLED is false
04-23 16:46:31.497: I/System.out(23621): AsyncTask #1(ApacheHTTPLog):Resquest instance of HttpUriRequesttrue
04-23 16:46:31.497: I/System.out(23621): AsyncTask #1(ApacheHTTPLog):determineRoute Local address : null
04-23 16:46:31.497: I/System.out(23621): AsyncTask #1(ApacheHTTPLog):Inside DefaultClientConnectionOperator.openConnection()
04-23 16:46:31.497: I/System.out(23621): AsyncTask #1(ApacheHTTPLog):start to get IP for host mydomin at time 1398257191507
04-23 16:46:31.497: I/System.out(23621): AsyncTask #1(ApacheHTTPLog):finish to get IP for host my domain at time 1398257191509, result number 1
04-23 16:46:31.507: I/System.out(23621): AsyncTask #1(ApacheHTTPLog):DefaultClientConnectionOperator.openConnection()InetAddress.getAllByName length:1
04-23 16:46:31.507: I/System.out(23621): AsyncTask #1(ApacheHTTPLog):DefaultClientConnectionOperator.openConnection() connsock Socket[address=/mydomain,port=8080,localPort=48526]
04-23 16:46:31.517: I/System.out(23621): AsyncTask #1(ApacheHTTPLog):Servers selected Ip address is : my domain
04-23 16:46:31.787: I/System.out(23621): AsyncTask #1(ApacheHTTPLog):HttpClientParams.isRedirecting(params) : true
04-23 16:46:31.787: I/System.out(23621): AsyncTask #1(ApacheHTTPLog):this.redirectHandler.isRedirectRequested(response, context) : false

由于多个 Get Request 会造成内存泄漏并中断 AsyncThread

try {

            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();

            // String encodeUrl = URLEncoder.encode(urlStr, "UTF-8");

            HttpGet httpGet = new HttpGet(urlStr);
            httpGet.addHeader("accept", "application/json");
            httpGet.addHeader("Host", prefs.getString("DomainName", ""));
            httpGet.addHeader("Cookie", prefs.getString("MyCookie", ""));

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            inputStream = httpEntity.getContent();



} catch (Exception e) {
    e.printStackTrace();
}

内存泄漏如下

W/SingleClientConnManager(4564): Invalid use of SingleClientConnManager: connection still allocated. 04-23 17:28:22.678: W/SingleClientConnManager(4564): Make sure to release the connection before allocating another one
4

1 回答 1

2

您需要关闭 inputStream 以释放连接,然后再进行另一个连接。您可以通过调用entity.consumeContent(); 另一种方法来解决此问题,即配置您的 HttpClient 以使用ThreadSafeClientConnectionManager. 这将使您能够一次建立多个连接。

在任何一种情况下,调用 consumeContent 来释放连接都很重要。

下面是一些示例代码,我用它来设置带有 ThreadSafeClientConnectionManager 的单例 HttpCLient:

public class SingletonClient extends DefaultHttpClient {

    private static SingletonClient instance = null;
    private static String userAgentString = "";

    public static synchronized SingletonClient getInstance() {
            if (instance == null) {
                HttpParams httpParameters = new BasicHttpParams();
                ConnManagerParams.setMaxTotalConnections(httpParameters, 100);
                HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
                int timeoutConnection = 40000;
                HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
                int timeoutSocket = 40000;
                HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
                HttpProtocolParams.setUseExpectContinue(httpParameters, false);
                HttpProtocolParams.setUserAgent(httpParameters, userAgentString + " " + HttpProtocolParams.getUserAgent(httpParameters));

                SchemeRegistry schemeRegistry = new SchemeRegistry();

                SSLSocketFactory sf = SSLSocketFactory.getSocketFactory();
                sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
                schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
                schemeRegistry.register(new Scheme("https", sf, 443));

                ClientConnectionManager cm = new ThreadSafeClientConnManager(httpParameters, schemeRegistry);

                instance = new SingletonClient(cm, httpParameters);
            }
            return instance;
        }
}
于 2014-08-01T14:18:03.517 回答