OKHttp3网络请求工具类

依赖

  1. //okHttp3
    implementation ‘com.squareup.okhttp3:okhttp:3.9.0’

  2. //打印日志
    implementation ‘com.squareup.okhttp3:logging-interceptor:3.6.0’
    例: 在这里插入图片描述

混淆文件

#OkHttp3混淆配置
-dontwarn com.squareup.okhttp3.**
-keep class com.squareup.okhttp3.** { *;}
-dontwarn okio.**

HttpHelper

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.sxzb.devicezh.entity.DataEntity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.ConnectionPool;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * 作者:xujiahui
 * 时间:2019/3/12
 * 作用:ok网络请求
 */
public class HttpHelper {
    private final OkHttpClient okHttpClient;
    private HttpRequestListener httpRequestListener;
    private static final int SUCCESS_REQUEST = 1;
    private static final int FAIL_REQUEST = 0;
    //测试版地址:http://dev.shop.trinitytech.com.cn
    //正式版地址:http://shop.trinitytech.com.cn
    //http://dev.trinitytech.com.cn/trinity-tripartite/baidu/map/reverse_geocoding
    //测试环境
    // private static final String baseUrl = "https://dev";
    //生产环境
    private static final String baseUrl = "https://cloud";
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    MediaType mediaType = MediaType.parse("application/octet-stream");//设置类型,类型为八位字节流
    //打印日志
    private HttpHelper(Context context) {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.e("HttpLoggingInterceptor", "++++++++" + message);
            }
        });
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        okHttpClient = new OkHttpClient.Builder().readTimeout(5, TimeUnit.MINUTES).writeTimeout(5, TimeUnit.MINUTES)
                .addInterceptor(logging)//添加这句
                .connectionPool(new ConnectionPool(5, 1, TimeUnit.SECONDS)).build();
    }

    /**
     * 单利模式
     * @param context
     * @return
     */
    public static HttpHelper getIntents(Context context) {
        return new HttpHelper(context);
    }

    public void setHttpRequestListener(HttpRequestListener httpRequestListener) {
        this.httpRequestListener = httpRequestListener;
    }


    public HttpHelper doPosJson(int type, String url, String json) {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder().url(baseUrl + url).post(body).build();
        doHttp(type, request);
        return this;
    }

    public HttpHelper doPost(int type, String url, RequestBody body) {
        Request request = new Request.Builder().url(url).post(body).build();
        doHttp(type, request);
        return this;
    }

    public HttpHelper doGetJson(int type, String url, String json) {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder().url(baseUrl + url).get().build();
        doHttp(type, request);
        return this;
    }

    public HttpHelper doPosJson(int type, String url, List<DataEntity> list) {

        JSONObject jsonObject = new JSONObject();
        for (int i = 0; i < list.size(); i++) {
            try {
                jsonObject.put(list.get(i).getName(), list.get(i).getValue());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        RequestBody body = RequestBody.create(JSON, jsonObject.toString());
        Request request = new Request.Builder().url(baseUrl + url).post(body).build();
        doHttp(type, request);
        return this;
    }


    private void doHttp(int type, final Request request) {

        final Message msg = Message.obtain();
        msg.arg1 = type;
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                msg.what = FAIL_REQUEST;
                msg.obj = e.getMessage();
                handler.sendMessage(msg);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                msg.what = SUCCESS_REQUEST;
                msg.obj = response.body().string();
                handler.sendMessage(msg);
            }
        });
    }


    @SuppressLint("HandlerLeak")
    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String data = (String) msg.obj;
            int type = msg.arg1;
            switch (msg.what) {
                case SUCCESS_REQUEST:
                    httpRequestListener.SuccessRequest(type, data);
                    break;
                case FAIL_REQUEST:
                    httpRequestListener.Filed(data);
                    break;
            }
        }
    };


}

HttpRequestListener

/**
 * 作者:xujiahui
 * 时间:2019/3/12
 * 作用:ok网络请求
 */
public interface HttpRequestListener {
    //成功
    void SuccessRequest(int type, String data);

    //失败
    void Filed(String msg);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值