代码
解释在注释里面
package com.example.okhttptest;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button send_request;
private TextView reponse_text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
send_request=findViewById(R.id.send_request);
reponse_text=findViewById(R.id.reponse_text);
send_request.setOnClickListener(this::onClick);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.send_request:
setSendrequestwithHttpURL();
break;
}
}
private void setSendrequestwithHttpURL() {
//开启线程发起网洛请求-**********
new Thread(new Runnable() {
@Override
public void run() {
try {
//创建实例
OkHttpClient client=new OkHttpClient();
//创建request对象
Request request=new Request.Builder().url("https://www.bilibili.com/").build();
//Response response=client.newCall(request).execute();发送请求并获得服务器返回的数据
Response response=client.newCall(request).execute();
String responseData=response.body().string();
showreponse(responseData);
}catch (Exception e){
e.printStackTrace();
}
}
}).start();
}
private void showreponse(String data){
runOnUiThread(new Runnable() {
@Override
public void run() {
reponse_text.setText(data);
}
});
}
}
|