mac
2024-07-16 3ec7de773bff5582411c6f1f659d35cf8fb1734a
app/src/main/java/com/hdl/photovoltaic/internet/HttpClient.java
@@ -9,13 +9,11 @@
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.hdl.hdlhttp.HxHttp;
import com.hdl.hdlhttp.HxHttpBuilder;
import com.hdl.hdlhttp.utils.GsonConvert;
import com.hdl.linkpm.sdk.core.api.HDLCloudUserApi;
import com.hdl.linkpm.sdk.core.exception.HDLException;
import com.hdl.linkpm.sdk.core.interceptor.HDLSmartHeader;
import com.hdl.linkpm.sdk.core.response.HDLResponse;
import com.hdl.linkpm.sdk.user.bean.HDLLoginBean;
import com.hdl.linkpm.sdk.user.callback.ILoginCallBack;
import com.hdl.linkpm.sdk.utils.HDLExceptionSubmitUtils;
import com.hdl.photovoltaic.bean.HttpResponsePack;
import com.hdl.photovoltaic.config.AppConfigManage;
@@ -23,7 +21,7 @@
import com.hdl.photovoltaic.listener.BaseSuccessFailureCallBeak;
import com.hdl.photovoltaic.listener.CloudCallBeak;
import com.hdl.photovoltaic.other.HdlLogLogic;
import com.hdl.photovoltaic.utils.HDLMD5Utils;
import com.hdl.photovoltaic.utils.Md5Utils;
import java.io.File;
import java.io.IOException;
@@ -34,19 +32,22 @@
import java.util.Objects;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
public class HttpClient {
    private static volatile HttpClient sHttpClient;
    private static final boolean isAddToMemory = false;
    public static synchronized HttpClient getInstance() {
        if (sHttpClient == null) {
@@ -61,7 +62,40 @@
    }
    /**
     * 请求服务器
     * 请求服务器(get)
     * 底层方法,引用库的方法
     *
     * @param requestUrl 请求绝对地址接口
     * @param callBack   回调
     * @return -
     */
    private Disposable requestGet(String requestUrl, CloudCallBeak<String> callBack) {
        HdlLogLogic.print("http---发送---" + requestUrl + "\r\n", isAddToMemory);
        //开发环境需要加(用来区分onpro和光伏app代码):HxHttp.builder().headers("x-lbs-version", "hdl-yt")
        return HxHttp.builder().url(requestUrl).build().get().subscribeWith(new HDLResponse<String>() {
            @Override
            public void onResponse(String str) {
                if (callBack != null) {
                    callBack.onSuccess(str);
//                          System.out.println("http---回复---" + requestUrl + "\r\n" + gson.fromJson(str, JsonObject.class).toString());
                    HdlLogLogic.print("http---回复---" + requestUrl + "\r\n" + str, isAddToMemory);
                }
            }
            @Override
            public void onFailure(HDLException e) {
                HDLExceptionSubmitUtils.submit(requestUrl, "", e);
                if (callBack != null) {
                    callBack.onFailure(e);
                    HdlLogLogic.print("http---回复---" + requestUrl + "\r\n" + "\"{code=\"" + e.getCode() + "," + "\"message=\"" + e.getMsg() + "}", isAddToMemory);
                }
            }
        });
    }
    /**
     * 请求服务器(post)
     * 底层方法,引用库的方法
     *
     * @param api      请求接口
@@ -69,36 +103,29 @@
     * @param callBack 回调
     * @return -
     */
    private Disposable request(String api, String body, CloudCallBeak<String> callBack) {
    private Disposable requestPost(String api, String body, CloudCallBeak<String> callBack) {
        String requestUrl = HDLCloudUserApi.getRequestUrl(api);
        Gson gson = new Gson();
        System.out.println("http->发送->" + requestUrl + "\r\n" + body);
        return HxHttp.builder()
                .url(requestUrl)
                .raw(body)
                .build()
                .post()
                .subscribeWith(new HDLResponse<String>() {
                    @Override
                    public void onResponse(String str) {
                        if (callBack != null) {
                            callBack.onSuccess(str);
//                          System.out.println("http->回复->" + requestUrl + "\r\n" + gson.fromJson(str, JsonObject.class).toString());
                            System.out.println("http->回复->" + requestUrl + "\r\n" + str);
                        }
                    }
        HdlLogLogic.print("http---发送---" + requestUrl + "\r\n" + body, isAddToMemory);
        //开发环境需要加(用来区分onpro和光伏app代码):HxHttp.builder().headers("x-lbs-version", "hdl-yt")
        return HxHttp.builder().url(requestUrl).raw(body).build().post().subscribeWith(new HDLResponse<String>() {
            @Override
            public void onResponse(String str) {
                if (callBack != null) {
                    callBack.onSuccess(str);
//                          System.out.println("http---回复---" + requestUrl + "\r\n" + gson.fromJson(str, JsonObject.class).toString());
                    HdlLogLogic.print("http---回复---" + requestUrl + "\r\n" + str, isAddToMemory);
                }
            }
                    @Override
                    public void onFailure(HDLException e) {
                        HDLExceptionSubmitUtils.submit(requestUrl, body, e);
                        if (callBack != null) {
                            callBack.onFailure(e);
                            System.out.println("http->回复->" + requestUrl + "\r\n" + "\"{code=\"" + e.getCode() + "," + "\"message=\"" + e.getMsg() + "}");
                        }
                    }
                });
            @Override
            public void onFailure(HDLException e) {
                HDLExceptionSubmitUtils.submit(requestUrl, body, e);
                if (callBack != null) {
                    callBack.onFailure(e);
                    HdlLogLogic.print("http---回复---" + requestUrl + "\r\n" + "\"{code=\"" + e.getCode() + "," + "\"message=\"" + e.getMsg() + "}", isAddToMemory);
                }
            }
        });
    }
@@ -111,60 +138,97 @@
     * @param callBack 回调
     * @return -
     */
    private Disposable requestFile(String api, File body, CloudCallBeak<String> callBack) {
    private Disposable requestFilePost(String api, File body, CloudCallBeak<String> callBack) {
        String requestUrl = HDLCloudUserApi.getRequestUrl(api);
        Gson gson = new Gson();
        System.out.println("http->发送->" + requestUrl + "\r\n" + body);
        return HxHttp.builder()
                .url(requestUrl)
                .file(body)
                .build()
                .post()
                .subscribeWith(new HDLResponse<String>() {
                    @Override
                    public void onResponse(String str) {
                        if (callBack != null) {
                            callBack.onSuccess(str);
//                          System.out.println("http->回复->" + requestUrl + "\r\n" + gson.fromJson(str, JsonObject.class).toString());
                            HdlLogLogic.print("http->回复->" + requestUrl + "\r\n" + str, true);
                        }
                    }
        HdlLogLogic.print("http---发送---" + requestUrl + "\r\n" + body, isAddToMemory);
        return HxHttp.builder().url(requestUrl).file(body).build().post().subscribeWith(new HDLResponse<String>() {
            @Override
            public void onResponse(String str) {
                if (callBack != null) {
                    callBack.onSuccess(str);
//                          System.out.println("http---回复---" + requestUrl + "\r\n" + gson.fromJson(str, JsonObject.class).toString());
                    HdlLogLogic.print("http---回复---" + requestUrl + "\r\n" + str, isAddToMemory);
                }
            }
                    @Override
                    public void onFailure(HDLException e) {
                        HDLExceptionSubmitUtils.submit(requestUrl, body, e);
                        if (callBack != null) {
                            callBack.onFailure(e);
                            HdlLogLogic.print("http->回复->" + requestUrl + "\r\n" + "\"{code=\"" + e.getCode() + "," + "\"message=\"" + e.getMsg() + "}", true);
                        }
                    }
                });
            @Override
            public void onFailure(HDLException e) {
                HDLExceptionSubmitUtils.submit(requestUrl, body, e);
                if (callBack != null) {
                    callBack.onFailure(e);
                    HdlLogLogic.print("http---回复---" + requestUrl + "\r\n" + "\"{code=\"" + e.getCode() + "," + "\"message=\"" + e.getMsg() + "}", isAddToMemory);
                }
            }
        });
    }
    /**
     * 请求服务器
     * 下载文件
     *
     * @param callBack -
     */
    public Disposable downLoadFile(String url, CloudCallBeak<ResponseBody> callBack) {
        return HxHttp.builder()
                .url(url)
                .headers(HDLSmartHeader.IGNORE_SIGN_HEADER, 1)
                .build()
                .download()
                .subscribe(new Consumer<ResponseBody>() {
                    @Override
                    public void accept(ResponseBody responseBody) throws Exception {
                        if (callBack != null) {
                            callBack.onSuccess(responseBody);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        /**
                         * 网络请求失败
                         * 具体可以自己实现
                         */
                        HDLExceptionSubmitUtils.submit(url, null, throwable);
                        if (callBack != null) {
                            callBack.onFailure(new HDLException(403, throwable.getMessage()));
                        }
                    }
                });
    }
    /**
     * 请求(get)服务器
     *
     * @param requestUrl 请求绝对地址接口
     * @param callBack   回调
     */
    public Disposable requestHttpGet(String requestUrl, CloudCallBeak<String> callBack) {
        return requestGet(requestUrl, callBack);
    }
    /**
     * 请求(post)服务器
     *
     * @param api      请求接口
     * @param body     请求参数(json)
     * @param callBack 回调
     */
    public Disposable requestHttp(String api, String body, CloudCallBeak<String> callBack) {
        return request(api, body, callBack);
        return requestPost(api, body, callBack);
    }
    /**
     * 请求服务器(上传文件)
     * 上传文件
     *
     * @param api      请求接口
     * @param body     请求参数(json)
     * @param callBack 回调
     */
    public Disposable requestHttpFile(String api, File body, CloudCallBeak<String> callBack) {
        return requestFile(api, body, callBack);
    public Disposable uploadingFile(String api, File body, CloudCallBeak<String> callBack) {
        return requestFilePost(api, body, callBack);
    }
@@ -196,6 +260,7 @@
        this.requestHttpServer(fullUrl, json, isBasicService, isExecute, baseSuccessCallBeak);
    }
    /**
     * 请求服务器的方法
     *
@@ -209,20 +274,17 @@
            @Override
            public void run() {
                try {
                    HdlLogLogic.print("http->发送->" + fullUrl + "\r\n" + json, false);
                    HdlLogLogic.print("http---发送---" + fullUrl + "\r\n" + json, isAddToMemory);
                    OkHttpClient okHttpClient = new OkHttpClient();
                    RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8"), getJson(json));
                    final Request request = new Request.Builder()
                            .url(fullUrl)//请求的url
                            .addHeader("Authorization", UserConfigManage.getInstance().getHeaderPrefix() + UserConfigManage.getInstance().getToken())
                            .post(requestBody)
                            .build();
                    final Request request = new Request.Builder().url(fullUrl)//请求的url
                            .addHeader("Authorization", UserConfigManage.getInstance().getHeaderPrefix() + UserConfigManage.getInstance().getToken()).post(requestBody).build();
                    if (isExecute) {
                        Response response = okHttpClient.newCall(request).execute();//同步
                        if (response.isSuccessful()) {
                            String s = Objects.requireNonNull(response.body()).string();
                            HttpResponsePack httpResponsePack = new Gson().fromJson(s, HttpResponsePack.class);
                            HdlLogLogic.print("http->回复->" + response.request().url() + "\r\n" + s, false);
                            HdlLogLogic.print("http---回复---" + response.request().url() + "\r\n" + s, isAddToMemory);
                            baseSuccessCallBeak.onSuccess(httpResponsePack);
                        } else {
@@ -235,7 +297,7 @@
                        call.enqueue(new Callback() {//异步
                            @Override
                            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                                HdlLogLogic.print("http->回复->" + "\r\n" + e.getMessage(), false);
                                HdlLogLogic.print("http---回复---" + "\r\n" + e.getMessage(), isAddToMemory);
                            }
                            @Override
@@ -245,7 +307,7 @@
                                    String s = Objects.requireNonNull(response.body()).string();
                                    HttpResponsePack httpResponsePack = new Gson().fromJson(s, HttpResponsePack.class);
                                    baseSuccessCallBeak.onSuccess(httpResponsePack);
                                    HdlLogLogic.print("http->回复->" + "\r\n" + s, false);
                                    HdlLogLogic.print("http---回复---" + "\r\n" + s, isAddToMemory);
                                } else {
                                    baseSuccessCallBeak.onFailure(new HDLException(response.code(), response.message()));
                                }
@@ -254,9 +316,36 @@
                    }
                } catch (Exception e) {
                    baseSuccessCallBeak.onFailure(new HDLException(-100, e.getMessage()));
                    HdlLogLogic.print("http->回复->" + "\r\n" + e.getMessage(), false);
                    HdlLogLogic.print("http---回复---" + "\r\n" + e.getMessage(), isAddToMemory);
                }
            }
        }).start();
    }
    /**
     * 请求服务器的方法
     *
     * @param url 绝对请求地址
     */
    private void requestHttpServer(String url, CloudCallBeak<String> cloudCallBeak) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient okHttpClient = new OkHttpClient();
                final Request request = new Request.Builder().url(url).build();
                try {
                    Response response = okHttpClient.newCall(request).execute();
                    String s = Objects.requireNonNull(response.body()).string();
                    if (cloudCallBeak != null) {
                        cloudCallBeak.onSuccess(s);
                    }
                } catch (Exception e) {
                    if (cloudCallBeak != null) {
                        cloudCallBeak.onSuccess(e.getMessage());
                    }
                }
            }
        }).start();
    }
@@ -285,9 +374,8 @@
     * @param json 所有字段使用urlParameter拼接,除了appSecret
     */
    private String getSign(JsonObject json, String appSecret) {
        String builder = jsonToUrlParameter(json) +
                appSecret;
        return HDLMD5Utils.encodeMD5(builder);
        String builder = jsonToUrlParameter(json) + appSecret;
        return Md5Utils.encodeMD5(builder);
    }
@@ -318,14 +406,10 @@
     * @return -
     */
    private boolean IfValueNeedSign(String valueStr) {
        if (TextUtils.isEmpty(valueStr))
            return false;
        if (TextUtils.isEmpty(valueStr)) return false;
        final char[] strChar = valueStr.substring(0, 1).toCharArray();
        final char firstChar = strChar[0];
        //System.out.println("getJSONType firstChar = "+firstChar);
        if (firstChar != '{' && firstChar != '[')
            return true;
        return false;
        return firstChar != '{' && firstChar != '[';
    }
}