4

我正在制作一个应用程序,其中涉及以 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;

}

}

4

2 回答 2

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());
于 2012-10-15T06:59:25.217 回答
0

看到这个帖子,遇到和你一样的问题

使用 HttpClient 的 HTTP Post 请求需要 2 秒,为什么?

你能确认它是否有效吗?

HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpClient httpclient = new DefaultHttpClient(params);
于 2012-10-15T09:37:38.460 回答