Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/228.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 多个Get请求无法正常工作_Android_Android Asynctask_Androidhttpclient_Android Async Http_Android Json - Fatal编程技术网

Android 多个Get请求无法正常工作

Android 多个Get请求无法正常工作,android,android-asynctask,androidhttpclient,android-async-http,android-json,Android,Android Asynctask,Androidhttpclient,Android Async Http,Android Json,我正在使用下面的函数,但有AsyncTask异常,尽管我得到了有效的响应,为什么会这样 public static void LoadServer(SharedPreferences prefs) { InputStream inputStream = null; String json = ""; String urlStr = ""; urlStr = String.format("http://mydomin/settings.php",

我正在使用下面的函数,但有AsyncTask异常,尽管我得到了有效的响应,为什么会这样

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请求创建内存泄漏并中断异步线程时

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

在建立另一个连接之前,需要关闭inputStream以释放连接。您可以通过调用
entity.consumerContent()来实现这一点
另一种方法是将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;
        }
}

你得到的是哪一个例外?发布正确的堆栈跟踪。我没有收到异常,但Aysnc任务在获得堆栈上的跟踪后退出。我的朋友,堆栈上的跟踪没有告诉我任何猜测。04-23 17:28:22.678:W/SingleClientConnManager(4564):SingleClientConnManager的使用无效:连接仍然分配。04-23 17:28:22.678:W/SingleClientConnManager(4564):确保在分配另一个连接之前释放该连接。