工程目录:
清单文件增加访问网络权限,防止Cleartext HTTP traffic to xxx not permitted错误设置CleartextTraffic=“true”
<uses-permission android:name="android.permission.INTERNET"/>android:usesCleartextTraffic="true"
Activity
package com.example.ex_eight;import androidx.appcompat.app.AppCompatActivity;import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;public class MainActivity extends AppCompatActivity {private Button btn;private TextView tv;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btn=findViewById(R.id.btn);tv=findViewById(R.id.tv);btn.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) { //事件处理new HttpTask().execute();}});}class HttpTask extends AsyncTask<Void,Void,String> {@Overrideprotected String doInBackground(Void... voids) { //耗时操作代码在后台进行String httpUrl = "http://www.zlm.design"; //域名字符串String resultData = ""; //结果字符串URL url = null; //URL对象try {url = new URL(httpUrl); //构造URL对象时需要使用异常处理} catch (MalformedURLException e) {Log.i("TAG", "URL对象创建失败!");}if(url != null) { //如果URL不为空时try {//有关网络操作时,需要使用异常处理HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); // 打开连接并转型//服务器返回数据字符流,网页文档编码一般为UTF-8或GBKInputStreamReader in = new InputStreamReader(urlConn.getInputStream(), "UTF-8");//为输出创建BufferedReaderBufferedReader buffer = new BufferedReader(in);String inputLine = null;while (((inputLine = buffer.readLine()) != null)) {resultData += inputLine + "\n"; //换行}in.close(); //关闭输入流urlConn.disconnect(); // 关闭HTTP连接} catch (IOException e) {resultData=e.getMessage();}} else {resultData = "url is null"; //当url为空时输出}return resultData;}@Overrideprotected void onPostExecute(String resultData) { //在后台数据提交后更新UI主线程if (resultData != null)tv.setText(resultData); //原生用法,更新UI工作在onPostExecute()方法里elsetv.setText("Sorry,the content is null");}}
}