多个获取请求无法正常工作

时间:2014-04-23 13:05:54

标签: android android-asynctask androidhttpclient android-async-http android-json

我正在使用以下功能但是有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

1 个答案:

答案 0 :(得分: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;
        }
}