工程目录:
清单文件增加访问网络权限,防止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;
@Override
protected 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() {
@Override
public void onClick(View v) { //事件处理
new HttpTask().execute();
}
});
}
class HttpTask extends AsyncTask<Void,Void,String> {
@Override
protected 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或GBK
InputStreamReader in = new InputStreamReader(urlConn.getInputStream(), "UTF-8");
//为输出创建BufferedReader
BufferedReader 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;
}
@Override
protected void onPostExecute(String resultData) { //在后台数据提交后更新UI主线程
if (resultData != null)
tv.setText(resultData); //原生用法,更新UI工作在onPostExecute()方法里
else
tv.setText("Sorry,the content is null");
}
}
}