在我的活动中,我正在调用一个函数:
JSONObject jObj = SupportFunctions.returnJSONObject(url);
该功能如下所示:
public static JSONObject returnJSONObject(String url) {
JSONObject jObj = null;
InputStream iS = null;
String result = null;
// HTTP
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
iS = entity.getContent();
}
catch (Exception e) {
Log.e("QUIZ", e.getMessage());
return null;
}
return jObj;
}
通话结果为:
Pick [Android Application] <terminated>Pick [Android Application]
<disconnected>DalvikVM [localhost:8600]
Pick [Android Application]
DalvikVM [localhost:8600] (may be out of synch)
Thread [<1> main] (Suspended (exception RuntimeException))
<VM does not provide monitor information>
ActivityThread.performLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 2295
ActivityThread.handleLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 2349
ActivityThread.access$700(ActivityThread, ActivityThread$ActivityClientRecord, Intent) line: 159
ActivityThread$H.handleMessage(Message) line: 1316
ActivityThread$H(Handler).dispatchMessage(Message) line: 99
Looper.loop() line: 137
ActivityThread.main(String[]) line: 5419
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
Method.invoke(Object, Object...) line: 525
ZygoteInit$MethodAndArgsCaller.run() line: 1187
ZygoteInit.main(String[]) line: 1003
NativeStart.main(String[]) line: not available [native method]
Thread [<11> Binder_3] (Running) (may be out of synch)
Thread [<10> Binder_2] (Running) (may be out of synch)
Thread [<9> Binder_1] (Running) (may be out of synch)
为什么呼叫会产生此错误? HttpResponse response = httpclient.execute(httppost);
似乎失败了!
答案 0 :(得分:1)
从你的问题,我可以看到主线程被暂停。假设您在主线程中执行HTTP请求,这可能是您的问题。通常它会产生一个NetworkOnMainThreadException,我相信当你继续使用调试器时会发生这种情况。
由于您不能在主线程中执行HTTP请求,因此解决方案可以是:
JSONArray mJsonArray;
// Inner class to do http request out from main thread
class HttpRequestTask extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... url) {
InputStream iS = null;
// HTTP
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url[0]);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
iS = entity.getContent();
}
catch (Exception e) {
Log.e("QUIZ", e.getMessage());
return null;
}
if (iS != null) {
mJsonArray = new JSONArray(urlInputStream.toString());
}
return null;
}
protected void onPostExecute(Long result) {
// A toast to inform that the http requeset just finished.
// The json object will be available in mJsonArray class field.
Toast.makeText(YourActivity.this, "HTTP request finished", Toast.LENGTH_SHORT).show();
}
}
最后,要创建异步任务并运行它:
new HttpRequestTask().execute(url);
答案 1 :(得分:0)
这可能不是问题,但我们永远不会知道:你是否在清单中要求获得互联网许可?
<uses-permission android:name="android.permission.INTERNET" />