一、在build.gradle文件里添加
implementation 'com.squareup.okhttp3:okhttp:4.9.0'
implementation 'com.squareup.okhttp3:okhttp:3.12.0'
implementation 'com.squareup.okio:okio:1.17.4'
implementation 'com.lzy.net:okgo:3.0.4'
implementation 'com.alibaba:fastjson:1.2.57'
implementation 'com.orhanobut:logger:2.2.0'
com.alibaba:fastjson:用于JSON解析,
com.orhanobut:logger:用于输出日志
二、在AndroidManifest.xml里添加
//支持网络请求
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
//其他
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" /> <uses-permission android:name="android.permission.READ_SMS" /> <uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.WRITE_CONTACTS" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application android:name=".App" android:allowBackup="true" android:icon="@mipmap/cookie" android:label="手机端测试" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.Drysister" android:usesCleartextTraffic="true">
//在App里初始化okgo
android:name=".App"
//不安全请求的限制级别,降低安全级别
//参考:解决:qemu_pipe_open_ns:62: Could not connect to the ‘pipe:qemud:network‘ service: Invalid argument 202_qemu_pipe_open_ns:62: could not connect to the 'pi-CSDN博客
android:usesCleartextTraffic="true"
三、新建App,初始化okgo、Logger
public class App extends Application { private static App mInstance; public static App getInstance() { if(mInstance==null){ mInstance=new App(); } return mInstance; } @Override public void onCreate() { super.onCreate(); mInstance = this; OkGo.getInstance().init(this). setOkHttpClient(new OkHttpClient.Builder() .readTimeout(10000L, TimeUnit.MILLISECONDS) .writeTimeout(10000L, TimeUnit.MILLISECONDS) .connectTimeout(10000L, TimeUnit.MILLISECONDS) .build()) .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE) //全局统一缓存时间,默认永不过期,可以不传 .setRetryCount(3) //全局统一超时重连次数,默认为三次, // 那么最差的情况会请求4次(一次原始请求,三次重连请求),不需要可以设置为0 .setCacheMode(CacheMode.NO_CACHE) .setCacheTime(-1L); //日志格式化 FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder() .showThreadInfo(false) // 是否显示线程信息 默认显示 上图Thread Infrom的位置 .methodCount(1) // 展示方法的行数 默认是2 上图Method的行数 .methodOffset(0) // 内部方法调用向上偏移的行数 默认是0 //.logStrategy(customLog) // 改变log打印的策略一种是写本地,一种是logcat显示 默认是后者(当然也可以自己定义) .tag("DCSYT") // 自定义全局tag 默认:PRETTY_LOGGER .build(); //在Application中初始化一下 Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy)); Logger.addLogAdapter(new DiskLogAdapter(){ @Override public boolean isLoggable(int priority, @Nullable String tag) { return BuildConfig.DEBUG; } }); // Logger.d("Start APP"); } }
四、OkGo
Map<String, String> localMap = new HashMap<>();
localMap.put("strdt", "2022-11-03 14:04:02");//strdt=2022-11-03 14:04:02
List<String> urlparams=new ArrayList<>();
List<File> fileparams=new ArrayList<>();
List<HttpParams.FileWrapper> filewrappers=new ArrayList<>();
String serveurl="https://stqmf.fzdc.cn/home/getTime";//
OkGo.<String>get(serveurl )//get<=>post 请求方式
.tag(this) // 请求的tag,主要用于取消对应的请求
// .isMultipart(true) //制使用multipart/form-data表单上传
// .isSpliceUrl(true) //制将params的参数拼接到url后面
.retryCount(3) // 超时重连次数
// .cacheKey("caceKey") // 设置当前请求的缓存key
// .cacheTime(5000) // 缓存的过期时间,单位毫秒
// .cacheMode(CacheMode.DEFAULT) // 缓存模式,详细请看第四部分,缓存介绍
// .headers("header1","headervalue1") // 添鞏玗禧弓罩谨加请求头参数
.params(localMap) // 添加请求参数
// .addUrlParams("key",urlparams)
// .addFileParams("key",fileparams)
// .addFileWrapperParams("key",filewrappers)
.execute(new StringCallback() {
@Override
public void onSuccess(Response<String> response) {
Logger.d("OkGo...onSuccess," + response.code() + "-" + response.body());
UserDto obj= JSON.parseObject(response.body().toString(),UserDto.class);
Logger.d(obj.data);
}
@Override
public void onError(Response<String> response) {
Logger.d("OkGo...onError," + response.code() + "-" + response.body());
}
});
五、OkHttpClient
//1.构建OkHttpClient实例 final OkHttpClient okHttpClient = new OkHttpClient.Builder() .connectTimeout(200, TimeUnit.SECONDS)//链接超时为2秒,单位为秒 .writeTimeout(200, TimeUnit.SECONDS)//写入超时 .readTimeout(200, TimeUnit.SECONDS)//读取超时 .build(); //创建线程,在子线程中运行 new Thread(new Runnable() { @Override public void run() { try { //1、异步get... //通过Builder辅助类构建Request对象,链式编程 String url="https://stqmf.fzdc.cn/home/getTime"; HttpUrl.Builder httpBuilder = HttpUrl.parse(url).newBuilder(); httpBuilder.addQueryParameter("strdt","2022-11-04 0:04:02"); Request request = new Request.Builder() .url(httpBuilder.build()) .get() .build(); //异步 okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { e.printStackTrace(); Logger.e("get异步响应失败==" + e.toString()); } @Override public void onResponse(@NotNull Call call, @NotNull okhttp3.Response response) throws IOException { String result = response.body().string(); Logger.e("get异步响应成功==" + result); UserDto obj=JSON.parseObject(result,UserDto.class); Logger.e(obj.data); } }); //2、同步GET // Request request = new Request.Builder() // .get()//get请求 // .url("https://stqmf.fzdc.cn/home/getTime")//请求地址 // .build();//构建 // //通过mOkHttpClient调用请求得到Call // final Call call = okHttpClient.newCall(request); // //执行同步请求,获取Response对象 // okhttp3.Response response = call.execute(); // // if (response.isSuccessful()) {//如果请求成功 // String string = response.body().string(); // Logger.e("get同步请求success==" + string); // //响应体的string()对于小文档来说十分方便高效,但是如果响应体太大(超过1M),应避免使用string()方法, // //因为它会把整个文档加载到内存中,对用超多1M的响应body,应该使用流的方式来处理。 // // //response.body().bytes();//字节数组类型 // //response.body().byteStream();//字节流类型 // //response.body().charStream();//字符流类型 // // } else { // Logger.e("get同步请求failure=="); // } //3、同步POST... // //提交键值对需要用到FormBody,FormBody继承自RequestBody // FormBody formBody = new FormBody.Builder() // //添加键值对(通多Key-value的形式添加键值对参数) // .add("key", "value") // .build(); // // final Request request = new Request.Builder() // .post(formBody) // .url("https://stqmf.fzdc.cn/home/getTime")//URL地址 // .build(); // // okhttp3.Response response = okHttpClient.newCall(request).execute(); // if (response.isSuccessful()) { // Logger.e("Post请求String同步响应success==" + response.body().string()); // } else { // Logger.e("Post请求String同步响应failure==" + response.body().string()); // } //4、异步POST... // okHttpClient.newCall(request).enqueue(new Callback() { // @Override // public void onFailure(@NotNull Call call, @NotNull IOException e) { // Logger.e("Post请求(键值对)异步响应failure==" + e.getMessage()); // } // // @Override // public void onResponse(@NotNull Call call, @NotNull okhttp3.Response response) throws IOException { // String result = response.body().string(); // Logger.e("Post请求(键值对)异步响应Success==" + result); // } // }); } catch (Exception e) { Logger.e("请求IOException==" + e.toString()); } } }).start();