非法论证HttpURLConnection

问题描述 投票:-1回答:1

我是android的新手。我正在学习android网络。我试图创建一个与HttpURLConnection的连接来跟踪响应代码为200,但我得到IllegalArgumentException。我使用Async任务执行此操作但无法纠正。任何帮助,将不胜感激。

这是我的代码:

package com.movies.usman.moviesmesh;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    TextView text;

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



       new CheckConnectionStatus().execute("http://google.com");

    }




class  CheckConnectionStatus extends AsyncTask<String, Void, String>
{



            @Override
            protected String doInBackground(String... params) {
                URL url = null;
                try {
                url = new URL(params[0]);
                } catch (MalformedURLException e) {
                e.printStackTrace();
                }
                try {
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                //Log.i("Reponse: ", String.valueOf(urlConnection.getResponseCode()));
                return String.valueOf(urlConnection.getResponseCode());
                } catch (IOException e) {
                Log.e("Error: ", e.getMessage(), e);
                }
            return null;
            }

            @Override
            protected void onPostExecute(String s) {
            super.onPostExecute(s);
            text.setText(s);
            }
            }



}
android httpurlconnection android-networking
1个回答
0
投票

您应该在onCreate中初始化TextView

text = (TextView) findViewById(R.id.yourViewId);

之前

new CheckConnectionStatus().execute("http://google.com");
© www.soinside.com 2019 - 2024. All rights reserved.