MainActivity 中只有一个 TextView 用于输出 GET 请求的结果:import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
TextView textView1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1 = findViewById(R.id.textView1);
AsyncGetHttp task_get = new AsyncGetHttp();
task_get.execute("https://www.baidu.com");
}
class AsyncGetHttp extends AsyncTask {
HttpURLConnection connection = null;
BufferedReader reader = null;
@Override
protected void onPreExecute() {
// 任务刚开始的时候执行
}
@Override
protected String doInBackground(String... params) {
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
// 不使用缓存
connection.setUseCaches(false);
// 应该指的是与服务器建立连接的最大时间
connection.setConnectTimeout(1000);
// 读取数据的最大时间,两个最大时间不要设置得太短,不然会很容易出现超时的异常
connection.setReadTimeout(6000);
// 如果不是正常的请求结果则抛出异常,注意获取结果的步骤一定要在请求内容给完之后
if (connection.getResponseCode() != 200) {
throw new Exception("http error:" + connection.getResponseCode() + "," + connection.getResponseMessage());
}
// 使用 InputStream 进行接收操作
InputStream input = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(input));
StringBuilder response = new StringBuilder();
// 这里把 reader 中的内容一行行地读取到 response 中
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
// 返回最终的结果
return response.toString();
} catch (Exception ex) {
// 返回错误消息
return ex.getMessage();
} finally {
// 请求结束后释放资源
if (reader != null) {
try {
reader.close();
} catch (Exception ignore) {
}
}
if (connection != null) {
connection.disconnect();
}
}
}
@Override
protected void onProgressUpdate(Float... progresses) {
// 处理进度报告
}
@Override
protected void onPostExecute(String result) {
// 任务完成就会到此
textView1.setText(result);
}
@Override
protected void onCancelled() {
// 主动取消任务
}
}
}
这里定义了一个继承自 AsyncTask 的内部类,使用内部类的原因是在 AsyncTask 的 onPostExecute 回调方法中能够直接使用 MainActivity 创建时获取的 TextView 对象。