我是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);
}
}
}
答案 0 :(得分:0)
您应该在onCreate中初始化TextView
text = (TextView) findViewById(R.id.yourViewId);
之前的
new CheckConnectionStatus().execute("http://google.com");