我正在尝试使用下面的代码从服务器下载 json 文件。但是,我的应用程序表现得很奇怪。有时,json 会在 1-2 秒内被下载,有时它会永远卡在这个函数上。我还尝试了其他下载方式,例如 HttpUrlConnection。然而,这也无济于事。任何人都可以建议我解决它!
public String getJSONString(String url) {
String json = null;
HttpClient httpclient = null;
try {
Log.d("MARKER","PARSING SE PEHLE");
HttpParams params = new BasicHttpParams();
Log.d("MARKER","1st line");
HttpClient httpclient = new DefaultHttpClient(params); 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"), 80000);
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());
}
Log.d("MARKER","DOWNLOAD COMPLETE");
HttpClientProvider.safeClose(httpclient);
return json;
}