在Android上缓慢的HttpPost请求

时间:2012-10-15 06:33:01

标签: android json http-post

我正在创建一个应用程序,其中一部分涉及以JSON格式从我的服务器下载数据。我正在使用HTTP Post来实现同样的目标。我正在下载的JSON文件大小约为2-3 Kb。我正在不同的线程上进行所有这些操作。

然而,我的应用程序的性能非常难以预测。我尝试调试它,发现有时我的应用程序卡在我正在创建HttpPost对象的行,有时它几乎不需要1-2秒来执行该行。可能是什么问题?是不是因为我的应用占用了大量内存?还有一件事,一旦我强行关闭它,我的应用程序第二次运行正常。谢谢 !

public String getJSONString(String url) {
    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) 
        {sb.append(line + "n");}
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }
    return json;

}

}

2 个答案:

答案 0 :(得分:1)

您可以尝试使用此代码..

                    // Create a new HttpClient and Post Header
        httpclient = new DefaultHttpClient();
        httppost = new HttpPost(your URL) 

        // Sending details in Json Format
        JSONObject holder = new JSONObject();
        try { 
                     ------------
                   --------------

                } catch (JSONException e1) {
            e1.printStackTrace();
        }

    StringEntity se = new StringEntity(holder.toString());
    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
    httppost.setEntity(se);
    response = httpclient.execute(httppost);



            // Sends data to server

        StringEntity se = new StringEntity(holder.toString());

        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
                "application/json"));

        httppost.setEntity(se);

        response = httpclient.execute(httppost);

        resp = response.toString();

        String responseServer = EntityUtils.toString(response.getEntity());

答案 1 :(得分:0)

我看到这篇文章时遇到了和你一样的问题

HTTP Post requests using HttpClient take 2 seconds, why?

你能确认它是否有效吗?

HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpClient httpclient = new DefaultHttpClient(params);