最近RN有一部分想用原生Android来实现
引入原生okHttp依赖
implementation "com.squareup.okhttp3:okhttp:4.8.0"
testImplementation("com.squareup.okhttp3:mockwebserver:4.8.0")
1.首先看Okhttp封装示例代码:
引入依赖:
package com.xxxx.huimai.net;
import com.xxxx.huimai.listener.OkhttpListener;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* 使用Okhttp的工具类
*/
public class OkhttpUtils {
public static final MediaType JSON
= MediaType.get("application/json; charset=utf-8");
private static OkHttpClient client = new OkHttpClient();
//api/category-list
public static void okHttpGet(String url, OkhttpListener okhttpListener){
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
if(okhttpListener!=null) {
okhttpListener.fair(call, e);
}
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
if(okhttpListener!=null){
okhttpListener.success(call,response);
}
}
});
}
public static void okHttpPost(String url,String json,OkhttpListener okhttpListener){
RequestBody body = RequestBody.create(json, JSON);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
if(okhttpListener!=null){
okhttpListener.fair(call,e);
}
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
if(okhttpListener!=null){
okhttpListener.success(call,response);
}
}
});
}
}
OkhttpListener示例代码
package com.xxxx.huimai.listener;
import okhttp3.Call;
import okhttp3.Response;
public interface OkhttpListener {
void success(Call call, Response response);
void fair(Call call,Exception e);
}
网友评论