okhttphelper

okhttphelper

okhttphelper

  • okhttphelper
  • OKHttpHelper.class
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//



import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import java.io.IOException;
import java.io.InputStream;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import okhttp3.Credentials;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.Request.Builder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class OKHttpHelper {
    public static final int CONNECT_TIMEOUT = 10;
    public static final int READ_TIMEOUT = 120;
    public static final int WRITE_TIMEOUT = 120;
    public static final String HTTP_REQUEST_HEAD = "Authorization";
    public static final MediaType APPLICATION_JSON = MediaType.parse("application/json; charset=utf-8");
    private static final RequestBody EMPTY_BODY;
    private static final Logger logger;
    private static final OkHttpClient client;
    private static final OkHttpClient sslClient;

    public OKHttpHelper() {
    }

    public static String get(String url) {
        isUrlNullOrEmpty(url);
        Request request = (new Builder()).url(url).build();
        return handleResponse(request, client);
    }

    public static String get(String url, List<OKHttpHelper.OkHttpParam> params) {
        isUrlNullOrEmpty(url);
        Request request = (new Builder()).url(componentUrl(url, params)).build();
        return handleResponse(request, client);
    }

    public static String getWithBasic(String url, String userName, String password) {
        isUrlNullOrEmpty(url);
        String credential = Credentials.basic(userName, password);
        Request request = (new Builder()).header("Authorization", credential).url(url).build();
        return handleResponse(request, client);
    }

    public static String getWithBasic(String url, List<OKHttpHelper.OkHttpParam> params, String userName, String password) {
        isUrlNullOrEmpty(url);
        String credential = Credentials.basic(userName, password);
        Request request = (new Builder()).header("Authorization", credential).url(componentUrl(url, params)).build();
        return handleResponse(request, client);
    }

    public static String getWithHeader(String url, List<OKHttpHelper.OkHttpParam> params, Map<String, String> headers) {
        isUrlNullOrEmpty(url);
        Builder builder = new Builder();
        headers.entrySet().forEach((entry) -> {
            builder.addHeader((String)entry.getKey(), (String)entry.getValue());
        });
        Request request = builder.url(componentUrl(url, params)).build();
        return handleResponse(request, client);
    }

    public static String sslGet(String url) {
        isUrlNullOrEmpty(url);
        Request request = (new Builder()).url(url).build();
        return handleResponse(request, sslClient);
    }

    public static String sslGet(String url, List<OKHttpHelper.OkHttpParam> params) {
        isUrlNullOrEmpty(url);
        Request request = (new Builder()).url(componentUrl(url, params)).build();
        return handleResponse(request, sslClient);
    }

    public static String post(String url) {
        isUrlNullOrEmpty(url);
        Request request = (new Builder()).url(url).post(EMPTY_BODY).build();
        return handleResponse(request, client);
    }

    public static String post(String url, List<OKHttpHelper.OkHttpParam> params) {
        isUrlNullOrEmpty(url);
        RequestBody body = RequestBody.create(APPLICATION_JSON, convertListToJson(params));
        Request request = (new Builder()).url(url).post(body).build();
        return handleResponse(request, client);
    }

    public static String post(String url, String json) {
        isUrlNullOrEmpty(url);
        RequestBody body = RequestBody.create(APPLICATION_JSON, json);
        Request request = (new Builder()).url(url).post(body).build();
        return handleResponse(request, client);
    }

    public static String postWithBasic(String url, String userName, String password) {
        isUrlNullOrEmpty(url);
        String credential = Credentials.basic(userName, password);
        Request request = (new Builder()).header("Authorization", credential).url(url).post(EMPTY_BODY).build();
        return handleResponse(request, client);
    }

    public static String postWithBasic(String url, List<OKHttpHelper.OkHttpParam> params, String userName, String password) {
        isUrlNullOrEmpty(url);
        RequestBody body = RequestBody.create(APPLICATION_JSON, convertListToJson(params));
        String credential = Credentials.basic(userName, password);
        Request request = (new Builder()).header("Authorization", credential).url(url).post(body).build();
        return handleResponse(request, client);
    }

    public static String postWithBasic(String url, String json, String userName, String password) {
        isUrlNullOrEmpty(url);
        if (logger.isDebugEnabled()) {
            logger.debug("Http Request Parameters:{}", json);
        }

        RequestBody body = RequestBody.create(APPLICATION_JSON, json);
        String credential = Credentials.basic(userName, password);
        Request request = (new Builder()).header("Authorization", credential).url(url).post(body).build();
        return handleResponse(request, client);
    }

    public static String postWithHeader(String url, String json, Map<String, String> headers) {
        isUrlNullOrEmpty(url);
        if (logger.isDebugEnabled()) {
            logger.debug("Http Request Parameters:{}", json);
        }

        RequestBody body = RequestBody.create(APPLICATION_JSON, json);
        Builder builder = new Builder();
        headers.entrySet().forEach((entry) -> {
            builder.addHeader((String)entry.getKey(), (String)entry.getValue());
        });
        Request request = builder.url(url).post(body).build();
        return handleResponse(request, client);
    }

    public static String postForm(String url, Map<String, String> params) {
        isUrlNullOrEmpty(url);
        if (logger.isDebugEnabled()) {
            logger.debug("Http Request Parameters:{}", params);
        }

        okhttp3.FormBody.Builder formBody = new okhttp3.FormBody.Builder();
        params.keySet().forEach((key) -> {
            formBody.add(key, (String)params.get(key));
        });
        Request request = (new Builder()).url(url).post(formBody.build()).build();
        return handleResponse(request, client);
    }

    public static String sslPost(String url) {
        isUrlNullOrEmpty(url);
        Request request = (new Builder()).url(url).post(EMPTY_BODY).build();
        return handleResponse(request, sslClient);
    }

    public static String sslPost(String url, List<OKHttpHelper.OkHttpParam> params) {
        isUrlNullOrEmpty(url);
        RequestBody body = RequestBody.create(APPLICATION_JSON, convertListToJson(params));
        Request request = (new Builder()).url(url).post(body).build();
        return handleResponse(request, sslClient);
    }

    public static InputStream download(String url) {
        Request request = (new Builder()).url(url).addHeader("Connection", "close").build();
        Response response = null;

        try {
            response = getClient().newCall(request).execute();
        } catch (IOException var4) {
            var4.printStackTrace();
            logger.error("下载失败", var4);
        }

        return response.body().byteStream();
    }

    public static String sslPost(String url, String json) {
        isUrlNullOrEmpty(url);
        if (logger.isDebugEnabled()) {
            logger.debug("Http Request Parameters:{}", json);
        }

        RequestBody body = RequestBody.create(APPLICATION_JSON, json);
        Request request = (new Builder()).url(url).post(body).build();
        return handleResponse(request, sslClient);
    }

    public static OkHttpClient getClient() {
        return client;
    }

    public static String componentUrl(String url, List<OKHttpHelper.OkHttpParam> params) {
        if (params != null && params.size() > 0) {
            StringBuffer stringBuffer = new StringBuffer(url);
            if (!url.substring(url.length() - 1).equals("?")) {
                stringBuffer.append("?");
            }

            params.stream().forEach((okHttpParam) -> {
                stringBuffer.append(String.format("%s=%s&", okHttpParam.getKey(), okHttpParam.getValue()));
            });
            url = stringBuffer.toString().substring(0, stringBuffer.toString().length() - 1);
            if (logger.isDebugEnabled()) {
                logger.debug("Http Request Parameters:{}", JSONArray.toJSONString(params));
            }
        }

        return url;
    }

    public static String handleResponse(Request request, OkHttpClient client) {
        try {
            long var1 = System.currentTimeMillis();
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String result = response.body().string();
                if (logger.isDebugEnabled()) {
                    logger.debug(String.format("Request Time: %s,Request Result: %s.", String.valueOf(System.currentTimeMillis() - var1), result));
                }

                return result;
            } else {
                throw new ZSYServiceException(String.format("Request %s Fail,Error Code: %s.", request.url().url(), response.code()));
            }
        } catch (IOException var6) {
            throw new ZSYServiceException(var6.getMessage());
        }
    }

    private static String convertListToJson(List<OKHttpHelper.OkHttpParam> params) {
        JSONObject object = new JSONObject();
        if (params != null && params.size() > 0) {
            params.stream().forEach((okHttpParam) -> {
                object.put(okHttpParam.getKey(), okHttpParam.getValue());
            });
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Http Request Parameters:{}", object.toJSONString());
        }

        return object.toJSONString();
    }

    private static void isUrlNullOrEmpty(String url) {
        if (Strings.isNullOrEmpty(url)) {
            throw new ZSYServiceException("Http Request Uri is null or empty!");
        } else {
            if (logger.isDebugEnabled()) {
                logger.info("Http Request Uri:{}", url);
            }

        }
    }

    public static OKHttpHelper.ZsyApiResult convertZsyApiCallBack(String result) {
        if (result.contains("{\"status\":0,\"error\":")) {
            return new OKHttpHelper.ZsyApiResult(false, JSONObject.parseObject(result).getString("error"), (String)null);
        } else if (result.contains("{\"status\":0,\"msg\":")) {
            return new OKHttpHelper.ZsyApiResult(false, JSONObject.parseObject(result).getString("msg"), (String)null);
        } else {
            return result.contains("{\"success\":0,") ? new OKHttpHelper.ZsyApiResult(false, JSONObject.parseObject(result).getString("msg"), (String)null) : new OKHttpHelper.ZsyApiResult(true, "", result);
        }
    }

    public static OKHttpHelper.ZsyApiResult convertApiCallBack4Java(String result) {
        return !result.contains("\"errCode\":\"00\"") ? new OKHttpHelper.ZsyApiResult(false, JSONObject.parseObject(result).getString("errMsg"), (String)null) : new OKHttpHelper.ZsyApiResult(true, "", result);
    }

    public static OKHttpHelper.ZsyApiResult convertWxApiCallBack(String result) {
        JSONObject object = JSONObject.parseObject(result);
        String errCode = object.getString("errcode");
        return !Strings.isNullOrEmpty(errCode) && !errCode.trim().equals("0") ? new OKHttpHelper.ZsyApiResult(false, object.getString("errmsg"), (String)null) : new OKHttpHelper.ZsyApiResult(true, "", result);
    }

    private static SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory sSLSocketFactory = null;

        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init((KeyManager[])null, (TrustManager[])null, new SecureRandom());
            sSLSocketFactory = sslContext.getSocketFactory();
        } catch (Exception var2) {
        }

        return sSLSocketFactory;
    }

    static {
        EMPTY_BODY = RequestBody.create(APPLICATION_JSON, (new JSONObject()).toJSONString());
        logger = LoggerFactory.getLogger(OKHttpHelper.class);
        client = (new okhttp3.OkHttpClient.Builder()).connectTimeout(10L, TimeUnit.SECONDS).readTimeout(120L, TimeUnit.SECONDS).writeTimeout(120L, TimeUnit.SECONDS).build();
        sslClient = (new OkHttpClient()).newBuilder().connectTimeout(10L, TimeUnit.SECONDS).readTimeout(120L, TimeUnit.SECONDS).writeTimeout(120L, TimeUnit.SECONDS).sslSocketFactory(createSSLSocketFactory(), new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        }).hostnameVerifier((hostname, session) -> {
            return true;
        }).build();
    }

    public static class ZsyApiResult {
        private boolean success;
        private String errMsg;
        private String data;

        public ZsyApiResult(boolean success, String errMsg, String data) {
            this.success = success;
            this.errMsg = errMsg;
            this.data = data;
        }

        public boolean isSuccess() {
            return this.success;
        }

        public String getErrMsg() {
            return this.errMsg;
        }

        public void setErrMsg(String errMsg) {
            this.errMsg = errMsg;
        }

        public String get() {
            if (this.success) {
                return this.data;
            } else {
                throw new ZSYApiException(this.errMsg);
            }
        }
    }

    public static class OkHttpParam {
        private String key;
        private String value;

        public OkHttpParam(String key, String value) {
            this.key = key;
            this.value = value;
        }

        public String getKey() {
            return this.key;
        }

        public void setKey(String key) {
            this.key = key;
        }

        public String getValue() {
            return this.value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值