在build.gradle
中引用如下代码
dependencies {
// define a BOM and its version
implementation(platform("com.squareup.okhttp3:okhttp-bom:4.10.0"))
// define any required OkHttp artifacts without version
implementation("com.squareup.okhttp3:okhttp")
implementation("com.squareup.okhttp3:logging-interceptor")
}
在AndroidManifest
的Application
节点中添加
android:usesCleartextTraffic="true"
在AndroidManifest
中添加网络请求
<uses-permission android:name="android.permission.INTERNET" />
<!-- 检查网络可用性 -->
创建HttpUtil.java
类
package com.example.myapplication;
//引包
import okhttp3.OkHttpClient;
import okhttp3.Request;
//http工具类封装
public class HttpUtil {
public static void sendOkHttpRequest(String address,okhttp3.Callback callback){
OkHttpClient client=new OkHttpClient();
Request request=new Request.Builder().url(address).build();
client.newCall(request).enqueue(callback);
}
}
异步调用HttpUtil
获取网络信息
HttpUtil.sendOkHttpRequest(url, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
//线程回到主线程,否则系统交出现错调
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.d("Web","Fail");
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseText = response.body().string();
//线程回到主线程,否则系统交出现错调
runOnUiThread(new Runnable() {
@Override
public void run() {
}
});
}
});
标签:com,void,okhttp3,使用,OkHttp,new,HttpUtil,public
From: https://www.cnblogs.com/MarkDespite/p/16661256.html