package wld.bawei.com.myjindong.AddMVP; import android.os.Handler; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.Map; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import wld.bawei.com.myjindong.CommonParamsInterceptor; /** * Created by 大金鑫 on 2017/12/15. */ public class AddOkHttp { private Handler handler=new Handler(); private static AddOkHttp addOkHttp; private String code; private AddOkHttp(){} public static AddOkHttp getInsentce(){ if(addOkHttp==null){ synchronized (AddOkHttp.class){ if(addOkHttp==null){ addOkHttp=new AddOkHttp(); } } } return addOkHttp; } public void doPost(String path, Map<String,String> map, final AddCallBack addCallBack){ OkHttpClient okHttpClient = new OkHttpClient.Builder() .addInterceptor(new CommonParamsInterceptor()) .build(); FormBody.Builder builder = new FormBody.Builder(); for(String key:map.keySet()){ builder.add(key,map.get(key)); } Request builder1 = new Request.Builder().post(builder.build()).url(path).build(); Call call = okHttpClient.newCall(builder1); call.enqueue(new Callback() { @Override public void onFailure(Call call, final IOException e) { handler.post(new Runnable() { @Override public void run() { addCallBack.onFailure(e.getMessage()); } }); } @Override public void onResponse(Call call, Response response) throws IOException { try { JSONObject jsonObject = new JSONObject(response.body().string()); code = jsonObject.optString("code"); handler.post(new Runnable() { @Override public void run() { addCallBack.onSuccess(code); } }); } catch (JSONException e) { e.printStackTrace(); } } }); } }
OkhttpPost加拦截器
最新推荐文章于 2024-07-02 16:42:09 发布
本文介绍了一个基于MVP架构的Android应用中如何利用OkHttp进行后台数据交互的方法。具体实现了通过POST请求发送数据,并对接口响应进行处理。文章详细展示了AddOkHttp类的设计思路及其实现细节。
摘要由CSDN通过智能技术生成