public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView responseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//按钮
Button sendRequest = (Button) findViewById(R.id.send_result);
//文本框
responseText = (TextView) findViewById(R.id.repose_text);
sendRequest.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v.getId() == R.id.send_result){
sendRequestHttp();
}
}
private void sendRequestHttp(){
//开启线程来发起网络请求
new Thread(new Runnable() {
@Override
public void run() {
try {
//创建OkHttpClient实例
OkHttpClient client = new OkHttpClient();
//发起一条http请求要创建Request
Request request = new Request.Builder()
.url("https://www.baidu.com") //设置网络地址
.build();
//execute()发送请求并回去服务器返回的数据 ;response就是服务器返回的数据
Response response = client.newCall(request).execute();
//获取返回的具体内容
String responseData = response.body().string();
showResponse(responseData);
}catch (Exception e){
e.printStackTrace();
}
}
}).start();
}
private void showResponse(final String response){
runOnUiThread(new Runnable() {
@Override
public void run() {
//讲结果显示到UI上面
responseText.setText(response);
}
});
}
}
注意记得添加依赖库:
implementation 'com.squareup.okhttp3:okhttp:3.4.1'
添加权限
<uses-permission android:name="android.permission.INTERNET"/>
其中还需要注意的是把Url中的http改为https这样就能显示内容了
来源:CSDN
作者:陌恋殇雪
链接:https://blog.csdn.net/weixin_38361026/article/details/103728987