gpt4 book ai didi

java - Android 在执行 HttpGet 请求时崩溃

转载 作者:行者123 更新时间:2023-12-01 12:13:58 24 4
gpt4 key购买 nike

我在 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();
}

日志猫:

    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)

最佳答案

您可能遇到的问题是您正在 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()。

关于java - Android 在执行 HttpGet 请求时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27115636/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com