效果图
加权限
<uses-permission android:name="android.permission.INTERNET"/>
build.gradle
//okhttp
implementation 'com.squareup.okhttp3:okhttp:3.12.0'
布局
<Button
android:id="@+id/bt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="get请求" />
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="match_parent" />
MainActivity
public class MainActivity extends AppCompatActivity {
private Button button;
private TextView textView;
public String string;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.bt);
textView = (TextView) findViewById(R.id.tv);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//1.okhttpClient对象
OkHttpClient okHttpClient = new OkHttpClient();
//2构造Request,
//builder.get()代表的是get请求,url方法里面放的参数是一个网络地址
Request.Builder builder = new Request.Builder();
Request request = builder.get().url("http://www.baidu.com/").build();
//3将Request封装成call
Call call = okHttpClient.newCall(request);
//4,执行call,这个方法是异步请求数据
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
//失败调用
Log.e("MainActivity", "onFailure: " );
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
//成功调用
Log.e("MainActivity", "onResponse: " );
//获取网络访问返回的字符串
string = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(string);
}
});
}
});
}
});
}
}