Android在执行HttpGet请求时崩溃

时间:2014-11-24 22:48:39

标签: java android xml http xmlhttprequest

我在Android中读取来自Http Url的XML响应时遇到了问题,虽然我在Java(eclipse)中尝试了相同的代码,但它在Android设备上崩溃了。

代码:

    try {
        URL url = new URL(link);
        HttpURLConnection request1 = (HttpURLConnection) url.openConnection();
        request1.setRequestMethod("GET");
        request1.connect();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

LogCat:

    11-25 01:11:28.853: D/AndroidRuntime(3600): Shutting down VM
11-25 01:11:28.853: W/dalvikvm(3600): threadid=1: thread exiting with uncaught exception (group=0x41832da0)
11-25 01:11:28.863: E/AndroidRuntime(3600): FATAL EXCEPTION: main
11-25 01:11:28.863: E/AndroidRuntime(3600): Process: com.example.qbuster, PID: 3600
11-25 01:11:28.863: E/AndroidRuntime(3600): java.lang.IllegalStateException: Could not execute method of the activity
11-25 01:11:28.863: E/AndroidRuntime(3600):     at android.view.View$1.onClick(View.java:3969)
11-25 01:11:28.863: E/AndroidRuntime(3600):     at android.view.View.performClick(View.java:4637)
11-25 01:11:28.863: E/AndroidRuntime(3600):     at android.view.View$PerformClick.run(View.java:19422)
11-25 01:11:28.863: E/AndroidRuntime(3600):     at android.os.Handler.handleCallback(Handler.java:733)
11-25 01:11:28.863: E/AndroidRuntime(3600):     at android.os.Handler.dispatchMessage(Handler.java:95)
11-25 01:11:28.863: E/AndroidRuntime(3600):     at android.os.Looper.loop(Looper.java:136)
11-25 01:11:28.863: E/AndroidRuntime(3600):     at android.app.ActivityThread.main(ActivityThread.java:5586)
11-25 01:11:28.863: E/AndroidRuntime(3600):     at java.lang.reflect.Method.invokeNative(Native Method)

2 个答案:

答案 0 :(得分:1)

您可能遇到的问题是您正在UI(主)线程上执行网络操作。一种简单的解决方法是启动一个新线程并在后台执行操作。您可以将Asynctask类用于此目的,如下所示:

private class AsyncCaller extends AsyncTask<Void, Void, Void>
{

@Override
protected void onPreExecute() {
    super.onPreExecute();

    //This runs on UI thread still.
}

@Override
protected Void doInBackground(Void... params) {

    //This runs in the background. Make your network operations here


    return null;
}

@Override
protected void onPostExecute(Void result) {
    super.onPostExecute(result);

 //This method will be running on UI thread
 //This is called when onBackground ha finished

}

}

然后,您可以实例化AsyncCaller并在其上调用execute()。

答案 1 :(得分:0)

您是否检查过AndroidManifest.xml上的互联网权限?

<uses-permission android:name="android.permission.INTERNET"></uses-permission>