HttpUrlConnection 应用程序在 ICS 上崩溃

HttpUrlConnection App Crashes on ICS

方法 sendMessage(View view) 在单击按钮时运行。该方法被成功调用,因为 t.setText("Checking..."); 将文本按预期更改为 Checking...

问题是当 s= urlConnection.getResponseCode(); 未被注释掉时应用程序强制关闭。是因为没有建立连接还是我在代码中遗漏了什么?

我是 android 编程新手,找不到有关使用 HttpUrlConnection 的 Web 服务的适当指南或视频教程。在继续学习 REST、SOAP 或其他 API 之前,我想了解这一点。

我尝试了什么?

  1. Changed URL to a sub-domain I own but it still crashes.

  2. Searched on forums and Whosebug and came across something called AsyncTask. I am not sure if that's necessary here because I didn't find that as a requirement in Android Doc. I learnt most of the connection part from Android Doc since video tutorials didn't explain well.

    public class Main2Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

    }
    public void sendMessage(View view) throws IOException {
      
        TextView t=findViewById(R.id.hello2);
        t.setText("Checking...");
        URL url = new URL("http://google.com");
       HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        try {

            int s=0;
            s= urlConnection.getResponseCode();
            t.setText("Nice.");
        } finally {
            urlConnection.disconnect();
        }
     }
}

我知道使用 REST 和 SOAP 等 API 可以使事情变得更容易,但出于学习目的,我想这样做。如果有人可以指导我找到适当的教程或博客,那就太棒了。老实说,我在我提到的教程中找不到任何正确解释的内容。

你肯定不能这样做,为什么?

因为android中的主线程是UI线程,它不能像网络线程那样做长时间的操作,它不能等待它,但是任何显式线程都不会'无法访问 UI 线程,那么您应该怎么办?

您必须创建异步方法并且 httpUrlConnection 应该在 Class 内调用 AsyncTask 如果你确实需要在异步方法中编辑 UI 线程中的某些组件,那么你必须使用 Handlers 才能编辑其中的一些组件,因此只有在你这样做时你的代码才能工作类似的东西

new AsyncTask<Void, Void, Void>() {

    @Override
    protected Void doInBackground( Void... voids ) {
        HttpURLConnection urlConnection = (HttpURLConnection) 
        url.openConnection();
        return null;
    }
}.execute();