嘿,今天的你过的还好吗,今天分享自己Android网络直接操作封装
没什么好讲的,就是直接封装起来就方便调用就ok了
package com.lnwl.digitalcertificate.util;
/**
* Author: lsx
* Description
* Date:2024-12-06 15:12
*/
import androidx.annotation.NonNull;
import com.lnwl.basic.util.ToastUtilsExt;
import java.io.IOException;
import java.util.Objects;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class okHttpUtil {
/**
* 网络相关
*/
private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
public static void getOkhttpRequest(String address, Callback callback) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(address)
.build();
client.newCall(request).enqueue(callback);
}
public static void postOkhttpRequest(String address, String data,IOnAction i ) {
RequestBody requestBody = RequestBody.create(JSON, data);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(address)
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
ToastUtilsExt.info(e.getMessage());
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
i.onCheckListener(response.body().string());
}
});
}
public static String postJsonRequest(String address, String data) throws IOException {
RequestBody requestBody = RequestBody.create(JSON, data);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(address)
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
return Objects.requireNonNull(response.body()).string();
}
interface IOnAction {
void onCheckListener(String result);
}
}