//异步任务处理 //创建内部类,来实现网络异步请求 //新建内部类 继承 AsyncTask @SuppressLint("StaticFieldLeak") class RequestNetworkDataTask extends AsyncTask{ @Override protected void onPreExecute() { super.onPreExecute(); textView.setText("加载中"); //主线程 } @Override protected String doInBackground(String[] strings) { String result = requestData(strings[0]); return result; //子线程,需要异步执行的命令在此执行 } @Override protected void onPostExecute(String s) { super.onPostExecute(s); textView.setText(s); //主线程 //异步代码处理完后,在主线程中进行进一步操作 } }
在需要调用这个自定义内部类的地方使用以下代码
String url = getEditTextUrl(); new RequestNetworkDataTask().execute(url);
下面是通过EditText 获取输入的网址
通过点击Button 在下方的TextView中显示网址对应的网站源码
public class NetworkActivity extends AppCompatActivity implements View.OnClickListener { private EditText editText; private Button btn; private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_network); initView(); btn.setOnClickListener(this); } private void initView() { editText = findViewById(R.id.act_network_url_et); btn = findViewById(R.id.act_network_getNet_btn); textView = findViewById(R.id.act_network_show_tv); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.act_network_getNet_btn: String url = getEditTextUrl(); new RequestNetworkDataTask().execute(url); break; } } private String getEditTextUrl() { return editText != null ? editText.getText().toString() : ""; } private String requestData(String urlString) { try { URL url = new URL(urlString); //打开Url HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //设置超时时间 connection.setConnectTimeout(5000); //设置请求方法 connection.setRequestMethod("GET"); //开始请求 connection.connect(); int response = connection.getResponseCode(); //请求的消息 String reponseMessage = connection.getResponseMessage(); InputStream inputStream = connection.getInputStream(); Reader reader = new InputStreamReader(inputStream, "UTF-8"); char[] buffer = new char[1024 * 8]; reader.read(buffer); String content = new String(buffer); return content; } catch (IOException e) { e.printStackTrace(); } return null; } //异步任务处理 //创建内部类,来实现网络异步请求 @SuppressLint("StaticFieldLeak") class RequestNetworkDataTask extends AsyncTask{ @Override protected void onPreExecute() { super.onPreExecute(); textView.setText("加载中"); //主线程 } @Override protected String doInBackground(String[] strings) { String result = requestData(strings[0]); return result; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); textView.setText(s); //主线程 } }}