okhttp3 get post 简单封装

时间:2022-08-14 18:58:04

最近打算在新项目中使用 okhttp3, 简单封装了一下异步 get post

因为 CallBack 也是在子线程中执行,所以用到了 Handler

public class MyOkHttpClient {
private static MyOkHttpClient myOkHttpClient;
private OkHttpClient okHttpClient;
private Handler handler; private MyOkHttpClient() {
okHttpClient = new OkHttpClient();
handler = new Handler(Looper.getMainLooper());
} public static MyOkHttpClient getInstance() {
if (myOkHttpClient == null) {
synchronized (MyOkHttpClient.class) {
if (myOkHttpClient == null) {
myOkHttpClient = new MyOkHttpClient();
}
}
} return myOkHttpClient;
} class StringCallBack implements Callback {
private HttpCallBack httpCallBack;
private Request request; public StringCallBack(Request request, HttpCallBack httpCallBack) {
this.request = request;
this.httpCallBack = httpCallBack;
} @Override
public void onFailure(Call call, IOException e) {
final IOException fe = e;
if (httpCallBack != null) {
handler.post(new Runnable() {
@Override
public void run() {
httpCallBack.onError(request, fe);
}
});
}
} @Override
public void onResponse(Call call, Response response) throws IOException {
final String result = response.body().string();
if (httpCallBack != null) {
handler.post(new Runnable() {
@Override
public void run() {
httpCallBack.onSuccess(request, result);
}
});
}
}
} public void asyncGet(String url, HttpCallBack httpCallBack) {
Request request = new Request.Builder().url(url).build();
okHttpClient.newCall(request).enqueue(new StringCallBack(request, httpCallBack));
} public void asyncPost(String url, FormBody formBody, HttpCallBack httpCallBack) {
Request request = new Request.Builder().url(url).post(formBody).build();
okHttpClient.newCall(request).enqueue(new StringCallBack(request, httpCallBack));
} public interface HttpCallBack {
void onError(Request request, IOException e); void onSuccess(Request request, String result);
}
}

使用

FormBody formBody = new FormBody.Builder().add("username", "lesiefang").add("age", "28").build();
MyOkHttpClient.getInstance().asyncPost("http://192.168.94.131:5000/aaa/", formBody, new MyOkHttpClient.HttpCallBack() {
@Override
public void onError(Request request, IOException e) {
Log.d("aaa", e.toString());
} @Override
public void onSuccess(Request request, String result) {
textView.setText(result);
}
});

至于上传文件、下载文件什么的用到时再封装一个类似的方法就行了