0

如果在我的应用程序中使用此源代码,则第一次没有问题,但是如果我关闭 wifi 并尝试从 Web 服务获取一些资源,我的应用程序会抛出异常状态:发现泄漏,我使用 httpclient 的关闭方法,但没有任何变化,在使用此代码的两天后,会引发异常。

堆栈打印:

10-17 16:42:00.524: ERROR/AndroidHttpClient(931): Leak found
10-17 16:42:00.524: ERROR/AndroidHttpClient(931): java.lang.IllegalStateException: AndroidHttpClient created and never closed

代码 :

public String getRequest(String url, ArrayList<NameValuePair> nameValuePairs){
    String resp = "";

        HttpParams httpParameters = new BasicHttpParams();
        HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);
        HttpProtocolParams.setHttpElementCharset(httpParameters, HTTP.UTF_8);

        AndroidHttpClient httpclient = null;

        try {

            httpclient  = AndroidHttpClient.newInstance("V");

            httpclient.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);


            HttpPost httppost = new HttpPost(url);

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));  

            HttpResponse response = httpclient.execute(httppost);

            HttpEntity entity = response.getEntity();
            InputStream instream = entity.getContent();

            Reader reader = new InputStreamReader(instream, HTTP.UTF_8);

            StringBuilder buffer = new StringBuilder("");

            char[] tmp = new char[1024];
            int l;
            while ((l = reader.read(tmp)) != -1) {
                buffer.append(tmp, 0, l);
            }

            reader.close();

            resp = buffer.toString().replace("&quot;", "\"");

            Log.d("V", "RESPONSE:-----\n" + resp + "\n--------------");


        } catch (IOException e){

            Log.e("V IOException [Send Request]","IO Exception");
            if((e != null) && (e.getMessage() != null)){
                Log.e("V",e.getMessage().toString());
            }

        } catch (Exception e) { 

            Log.e("V Exception [Send Request]","Exception Requester");
            if((e != null) && (e.getMessage() != null)){
                Log.e("V",e.getMessage().toString());
            }

        }finally {
            if (httpclient != null && httpclient.getConnectionManager() != null) {
                httpclient.close();
                httpclient = null;
            }
        }

        return resp;

    }
4

2 回答 2

0

试试:httppost.abort(); 在最后。另外,我不认为为每个请求创建一个 httpclient 是一个好主意,我认为最好将 http 客户端创建为实例变量并为每个请求重用。

于 2012-12-10T12:29:37.960 回答
0

我可能会建议使用 EntityUtils 类来做你正在做的事情,而不是你正在尝试做的事情。它将解决大部分问题

于 2014-04-07T14:12:02.227 回答