OKHttp封装类

     
public class MyOkhttp {

    private volatile static MyOkhttp myOkhttp;
    private static MultipartBody.Builder requestBody;
    private Gson gson;
    private OkHttpClient okHttpClient;


    private MyOkhttp() {
        super();
        gson = new Gson();
    }

    public static MyOkhttp getInstance() {
        if (myOkhttp == null) {
            synchronized (MyOkhttp.class) {
                if (myOkhttp == null) {
                    myOkhttp = new MyOkhttp();
                }
            }
        }
        return myOkhttp;
    }


    public void doRequest(Context context,String path, RequestType requestType, Map<String, String> map,
                          final MyCallBack mycallback, Type type) {

        Request.Builder builder = new Request.Builder();
        builder.url(path);
        if (requestType == RequestType.GET) {
            builder.get();
        } else if (requestType == RequestType.POST) {
            FormBody.Builder fBuilder = new FormBody.Builder();
            Set<Map.Entry<String, String>> entries =  map.entrySet();
            for (Map.Entry<String, String> e : entries) {
                fBuilder.add(e.getKey(), e.getValue());
            }
            FormBody fb = fBuilder.build();
            builder.post(fb);
        }
        Request request = builder.build();

        executeCall(context,request, mycallback, type);


    }


    private void executeCall(final Context context, Request request, final MyCallBack mycallback, final Type type) {
        okHttpClient = new OkHttpClient();
        Call call =  okHttpClient.newCall(request);
        mycallback.loading();
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mycallback.onFailure();
            }

            //200-300
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String string = response.body().string();
                    if (type == null) {
                        mycallback.checkIsLogin(context,string);
                        mycallback.onSuccess(string);
                    } else {
                        mycallback.checkIsLogin(context,string);
                        Object o = gson.fromJson(string, type);
                        mycallback.onSuccess(o);
                    }
                    //success
                } else {
                    //error
                    mycallback.onError();
                    Log.e("错误的code", "" + response.code());

                }

            }
        });

    }

    // 接口回掉
    private static final String TAG = "OkhttpUtils";
    private static Gson gson2 = new Gson();//创建gson对象
    private static String string;
    private static OkHttpClient client = new OkHttpClient();//okhttp对象

    public interface EntiyData {//创建接口

        void getEntiy(Object o);
    }
    private static EntiyData data;
    public static void setGetEntiydata(EntiyData data1) {
        data = data1;
    }

    public static void postMuti(Map<String, String> map, String path, final Context context, final Type cla, ArrayList<String> imgs) {
        MultipartBody.Builder builder = new MultipartBody.Builder();

        Set<Map.Entry<String, String>> entries = map.entrySet();//用entryset的方法遍历map集合
        for (Map.Entry<String, String> entry : entries) {
            builder.addFormDataPart(entry.getKey(), entry.getValue());
        }
        if (imgs!=null&&!imgs.isEmpty()){
            for (String str:imgs) {
                String newStr = str.replace("file://", "");
                File file = new File(newStr);
                RequestBody fileBody = RequestBody.create(MediaType.parse("image/png"),file);
                builder.addFormDataPart("photo",file.getName(), fileBody);
            }
        }
        MultipartBody requestBody = builder.setType(MultipartBody.FORM).build();
        Request request = new Request.Builder()
                .url(path)
                .post(requestBody)
                .build();
        Call call = client.newCall(request);
        //用这种方法不用创建子线程
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("联网失败,检查网络");
                //Toast.makeText(context, "下载数据失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    string = response.body().string();
                    Log.i(TAG, "获取的数据:" + string);
                    Object o = gson2.fromJson(string, cla);
                    //回调结果
                    data.getEntiy(o);
                } else {
                    Log.e(TAG, "失败");
                }
            }

        });
    }
    public interface GetEntityCallBack{
        void getEntity(Object obj);
    }
    public static GetEntityCallBack callback;
    public static void setGetEntityCallBack(GetEntityCallBack data1) {
        callback = data1;
    }
    public static Object o;
    /*
        * get
        * */
    public static void getData(String path, final Class cla) {

        OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(path)
                .get()
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String json = response.body().string();

                    Log.i(TAG, "onResponse: " + json);
                    Gson gson = new Gson();
                    o = gson.fromJson(json, cla);
                    //4.
                    callback.getEntity(o);
                }
            }
        });
    }





    public enum RequestType {
        GET,
        POST,
    }

}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值