我有一个从服务器下载 JSON 字符串的程序。直到最近,当我尝试打电话时,一切都很好
jsonReader.execute(getUrl).get();
其中 jsonReader 是用于下载 JSON 字符串的 AsyncTask,而 getUrl 是要执行的 URL。这个方法永远不会被执行,奇怪的是,它可以在我的手机上运行。
这是我的代码
调用json字符串阅读器的方法
private PointOfInterest getPointWithID(int id) {
String getUrl;
JSONReader jsonReader = new JSONReader();
try {
Log.d(TAG,"Trying to get ID: " + id);
getUrl = url + String.valueOf(id);
Log.d(TAG,"Trying to get json from: " + id); <-- Last Log line to get printed when run on emulator
jsonReader.execute(getUrl).get();
} catch (Exception e) {
e.printStackTrace();
}
String jsonString = jsonReader.returnJSONString();
Log.d(TAG,"Downloaded: " + jsonString);
//System.out.println("JSON: " + jsonString);
JSONResponse jsonResponse = JSONResponse.convertJSONToResponse(jsonString);
//System.out.println("JSON RESPONSE " + jsonResponse);
return jsonResponse.getPointofInterest();
}
jsonReader
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.util.Log;
/**
* Read JSON Strings
* @author Tom
*
*/
public class JSONReader extends AsyncTask <String, Void, String> {
String result;
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
StringBuilder sb = new StringBuilder();
String TAG = "JSONReader";
// constructor
public JSONReader() {
result = "";
}
@Override
protected String doInBackground(String... url) {
Log.d(TAG, "Executing " + url); <--Does not get printed when run on emulator
HttpPost httppost = new HttpPost(url[0]);
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
// json is UTF-8 by default i believe
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}catch(Exception e){
e.printStackTrace();
}
return result = sb.toString();
}
public String returnJSONString(){
return result;
}
}
我尝试重新启动 adb,制作新的 AVD,但似乎没有任何效果,我唯一的选择是在我的手机上进行测试,但是,由于我正在为 api 17 开发,这是不可取的。感谢您的帮助!