问题
I'm making an app a part of which involves downloading data from my server in JSON format. I'm using HTTP Post to achieve the same. The JSON file I'm downloading is around 2-3 Kb in size. I'm doing all these operations on a different thread.
However, the performance of my app is very unpredictable. I tried debugging it and found that sometimes my app gets stuck at line where I'm creating HttpPost object and sometimes it hardly takes 1-2 seconds to execute that line. What can be the issue ? Can it be because my app is taking lot of memory ? One more thing, my app runs fine second time once I force close it. Thanks !
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;
}
}
回答1:
you can try by this code..
// 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());
回答2:
I saw this post while having the same problem as you
HTTP Post requests using HttpClient take 2 seconds, why?
can you confirm if its working?
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpClient httpclient = new DefaultHttpClient(params);
来源:https://stackoverflow.com/questions/12890404/slow-httppost-request-on-android