学习内容:okhttp3同步请求和异步请求
OkHttp开源库进行访问
- 步骤:
1.app/build.gradle文件在dependencies闭包中添加如下内容: implementation ‘com.squareup.okhttp3:okhttp:4.4.0’ 2.创建OkHttpClient类的实例 OkHttpClient client = new OkHttpClient(); 3.创建Request对象(并设置目标地址、请求方式等) Request request = new Request.Builder() .url(“https://www.baidu.com”) //设置目标网络地址 .get() //默认为GET请求,可以省略 .build(); 4.调用newCall()方法来创建call对象 Call call = client.newCall(request); 5.发送请求并获取服务器返回的数据
学习内容:
textView = findViewById(R.id.t1);
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().get().
url("https://www.baidu.com").build();
final Call call = okHttpClient.newCall(request);
同步请求:*
textView = findViewById(R.id.t1);
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().get().
url("https://www.baidu.com").build();
final Call call = okHttpClient.newCall(request);
new Thread(new Runnable() {
@Override
public void run() {
try {
Response response = call.execute();
String sb = response.body().string();
replace(sb);
} catch (IOException e) {
e.printStackTrace();
}
}
public void replace(String sb) {
textView.setText(sb);
}
}).start();
易错点
异步请求:
**// 异步操作
call.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
//
// Toast.makeText(MainActivity.this, "请求失败", Toast.LENGTH_LONG).show();
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
// Toast.makeText(MainActivity.this, "请求成功", Toast.LENGTH_LONG).show();
final String shuju = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "请求成功", Toast.LENGTH_LONG).show();
textView.setText(shuju);
}
});
}
});**
易错点
|