All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.okhttp.OKHttpSender Maven / Gradle / Ivy

There is a newer version: 0.2.2
Show newest version
package com.okhttp;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import okhttp3.OkHttpClient.Builder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;

public class OKHttpSender {
    private static final Logger LOGGER = LoggerFactory.getLogger(OKHttpSender.class);
    private static OkHttpClient okHttpClient = null;
    private static String host = "";
    private static Headers headers;
    private static Headers respHeaders;
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private static final String REQUEST_URL_LOG_STYLE = "请求URL:{}";
    private static final String RESPONSE_LOG_STYLE = "******** {} ********";
    private static final String RESPONSE_LOG_TITLE = "HTTP Response";

    private OKHttpSender() {
    }

    private static void httpOrHttps(long...timeParams){
        long connectTimeoutInSecond = 10L, readTimeoutInSecond = 10L, writeTimeoutInSecond = 10L;
        if (timeParams != null && timeParams.length == 1){
            connectTimeoutInSecond = timeParams[0];
        } else if (timeParams != null && timeParams.length == 2){
            connectTimeoutInSecond = timeParams[0];
            readTimeoutInSecond = timeParams[1];
        }else if (timeParams != null && timeParams.length == 3){
            connectTimeoutInSecond = timeParams[0];
            readTimeoutInSecond = timeParams[1];
            writeTimeoutInSecond = timeParams[2];
        } else {
            LOGGER.info("其他情况采用默认设置。");
        }
        if (host.startsWith("https")){
            LOGGER.info("是Https请求");
            okHttpClient = new OkHttpClient().newBuilder()
                    .connectTimeout(connectTimeoutInSecond, TimeUnit.SECONDS)
                    .readTimeout(readTimeoutInSecond, TimeUnit.SECONDS)
                    .writeTimeout(writeTimeoutInSecond, TimeUnit.SECONDS)
                    .sslSocketFactory(SSLSocketClient.getSSLSocketFactory(), SSLSocketClient.getX509TrustManager())//配置
                    .hostnameVerifier(SSLSocketClient.getHostnameVerifier())//配置
                    .build();
        } else {
            okHttpClient = (new Builder())
                    .connectTimeout(connectTimeoutInSecond, TimeUnit.SECONDS)
                    .readTimeout(readTimeoutInSecond, TimeUnit.SECONDS)
                    .writeTimeout(writeTimeoutInSecond, TimeUnit.SECONDS)
                    .build();
        }
    }

    public static void initHost(String requestHost) {
        host = requestHost;
        httpOrHttps();
    }

    public static void initHost(String requestHost, long connectTimeoutInSecond, long readTimeoutInSecond) {
        host = requestHost;
        httpOrHttps(connectTimeoutInSecond, readTimeoutInSecond);
    }

    public static void initHost(String requestHost, String originCookies){
        host = requestHost;
        okHttpClient = (new Builder()).authenticator(new Authenticator(){
            @Override
            public Request authenticate(Route route, Response response) throws IOException
            {//401,认证
                String credential = Credentials.basic("[email protected]", "1234qwer");
                return response.request().newBuilder().header("Authorization", credential).build();
            }
        })
        .cookieJar(new CookieJar()
        {//这里可以做cookie传递,保存等操作
            @Override
            public void saveFromResponse(HttpUrl url, List cookies)
            {//可以做保存cookies操作
                LOGGER.info("cookies url: " + url.toString());
                for (Cookie cookie : cookies)
                {
                    LOGGER.info("cookies: " + cookie.toString());
                }
            }

            @Override
            public List loadForRequest(HttpUrl url)
            {//加载新的cookies
                LOGGER.info("url.host={}", url.host());
                LOGGER.info("url={}", url.url().toString());
                List cookies = new ArrayList<>();
                for(Entry entry : getCookieMap(originCookies).entrySet()){
                    LOGGER.info("从cookieMap获取当前Cookie:{}={}", entry.getKey(), entry.getValue());
                    Cookie cookie = new Cookie.Builder()
                            .hostOnlyDomain(url.host())
                            .name(entry.getKey()).value(entry.getValue())
                            .build();
                    cookies.add(cookie);
                }
                return cookies;
            }
        })
        .build();
    }

    private static Map getCookieMap(String originCookie){
        String[] pairGroup = originCookie.split(";");
        Map cookieMap = new HashMap<>();
        for(String pair : pairGroup){
            String[] currPair = pair.split("=");
            cookieMap.put(currPair[0].trim(), currPair[1].trim());
        }
        LOGGER.info("解析Cookies并存入cookieMap");
        return cookieMap;
    }

    public static void setHeaders(Map headersMap) {

        headers = Headers.of(headersMap);
        LOGGER.info("headers={}", headers.toString());


//        okhttp3.Headers.Builder headersBuilder = new okhttp3.Headers.Builder();
//        if (!headersMap.isEmpty()) {
//            for (Map.Entry entry : headersMap.entrySet()){
//                headersBuilder.add(entry.getKey(), entry.getValue());
//                LOGGER.info("增加header="+entry.getKey()+":"+entry.getValue());
//            }
//            headers = headersBuilder.build();
//        }

    }

    public static String sendGetRequest(String subUri, JSONObject reqParamJSONObject) {
        StringBuilder urlBuilder = new StringBuilder(host);
        StringBuilder paramBuilder = new StringBuilder("?");
        StringBuilder responseBuilder = new StringBuilder();
        Set keySet = reqParamJSONObject.keySet();
        Iterator iterator = keySet.iterator();
        int size = reqParamJSONObject.size();

        for(int i = 0; i < size; ++i) {
            String currKey = (String)iterator.next();
            paramBuilder.append(currKey);
            paramBuilder.append('=');
            paramBuilder.append(reqParamJSONObject.get(currKey));
            if (i != size - 1) {
                paramBuilder.append("&");
            }
        }

        String url = urlBuilder.append(subUri).append(paramBuilder).toString();
        LOGGER.info("请求URL:{}", url);
        Request.Builder requestBuilder = new Request.Builder();
        Request okHttp3Request = null;
        requestBuilder = requestBuilder.url(url);
        if (headers != null && headers.size() > 0){
            requestBuilder = requestBuilder.headers(headers);
            LOGGER.info("设置Headers完成。");
        }
        okHttp3Request = requestBuilder.build();
        LOGGER.info("Headers={}", headers.toString());

        try {
            Response okHttpResponse = okHttpClient.newCall(okHttp3Request).execute();
            LOGGER.info("******** {} ********", "HTTP Response");
            respHeaders = okHttpResponse.headers();
            String responseInfo = okHttpResponse.toString();
            LOGGER.info(responseInfo);
//            LOGGER.info(okHttpResponse.body().string()); // 这句可以成功输出响应。
            responseBuilder.append(okHttpResponse.body().string());

        } catch (IOException var14) {
            LOGGER.error("Exception happened during sending GetRequest.", var14);
        }
        LOGGER.info(responseBuilder.toString());
        return responseBuilder.toString();
    }


    public static String sendPostRequestWithJSONBody(String subUri, JSONObject reqBodyJSONObject) {
        StringBuilder urlBuilder = new StringBuilder(host);
        StringBuilder responseBuilder = new StringBuilder();
        String jsonString = reqBodyJSONObject == null ? "" : reqBodyJSONObject.toJSONString();
        RequestBody jsonBody = RequestBody.create(JSON, jsonString);
        String url = urlBuilder.append(subUri).toString();
        LOGGER.info("请求URL:{}", url);
        Request.Builder requestBuilder = new Request.Builder();
        if (headers != null) {
            requestBuilder.headers(headers);
        }

        Request okHttp3Request = requestBuilder.url(url).post(jsonBody).build();

        try {
            Response okHttpResponse = okHttpClient.newCall(okHttp3Request).execute();
            LOGGER.info("******** {} ********", "HTTP Response");
            respHeaders = okHttpResponse.headers();
            String responseInfo = okHttpResponse.toString();
            LOGGER.info(responseInfo);
            responseBuilder.append(okHttpResponse.body().string());
        } catch (IOException var11) {
            LOGGER.error("Exception happened during sending PostRequestWithJSONBody.", var11);
        }

        return responseBuilder.toString();
    }

    public static String sendDeleteRequestWithJSONBody(String subUri, JSONObject reqBodyJSONObject) {
        StringBuilder urlBuilder = new StringBuilder(host);
        StringBuilder responseBuilder = new StringBuilder();
        String jsonString = reqBodyJSONObject == null ? "" : reqBodyJSONObject.toJSONString();
        RequestBody jsonBody = RequestBody.create(JSON, jsonString);
        String url = urlBuilder.append(subUri).toString();
        LOGGER.info("请求URL:{}", url);
        Request.Builder requestBuilder = new Request.Builder();
        if (headers != null) {
            requestBuilder.headers(headers);
        }

        Request okHttp3Request = requestBuilder.url(url).delete(jsonBody).build();

        try {
            Response okHttpResponse = okHttpClient.newCall(okHttp3Request).execute();
            LOGGER.info("******** {} ********", "HTTP Response");
            respHeaders = okHttpResponse.headers();
            String responseInfo = okHttpResponse.toString();
            LOGGER.info(responseInfo);
            responseBuilder.append(okHttpResponse.body().string());
        } catch (IOException var11) {
            LOGGER.error("Exception happened during sending PostRequestWithJSONBody.", var11);
        }

        return responseBuilder.toString();
    }

    public static String sendAsyncPostRequestWithFormBody(String subUri, JSONObject reqFormJSONObject) {
        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        Iterator var3 = reqFormJSONObject.entrySet().iterator();

        while(var3.hasNext()) {
            Entry entry = (Entry)var3.next();
            formBodyBuilder.add((String)entry.getKey(), entry.getValue().toString());
        }

        RequestBody formBody = formBodyBuilder.build();
        StringBuilder urlBuilder = new StringBuilder(host);
        String url = urlBuilder.append(subUri).toString();
        LOGGER.info("请求URL:{}", url);
        Request.Builder requestBuilder = new Request.Builder();
        if (headers != null) {
            requestBuilder.headers(headers);
        }

        Request okHttp3Request = requestBuilder.url(url).post(formBody).build();
        Call call = okHttpClient.newCall(okHttp3Request);
        final StringBuilder responseBuilder = new StringBuilder();
        call.enqueue(new Callback() {
            public void onFailure(Call call, IOException e) {
                LOGGER.error(call.toString(), e);
            }

            public void onResponse(Call call, Response okHttpResponse) throws IOException {
                LOGGER.info("******** {} ********", "HTTP Response");
                respHeaders = okHttpResponse.headers();
                responseBuilder.append(okHttpResponse.body().string());
            }
        });
        return responseBuilder.toString();
    }


    /* New Added */

    public static String sendPostRequestWithJSONBody(String subUri, Object reqBodyObject) {
        StringBuilder urlBuilder = new StringBuilder(host);
        StringBuilder responseBuilder = new StringBuilder();
        String jsonString = "";
        if (reqBodyObject != null){
            if (reqBodyObject instanceof JSONObject || reqBodyObject instanceof JSONArray){
                jsonString = com.alibaba.fastjson.JSON.toJSONString(reqBodyObject);
            } else {
                jsonString = reqBodyObject.toString();
            }
        }

        RequestBody jsonBody = RequestBody.create(JSON, jsonString);
        String url = urlBuilder.append(subUri).toString();
        LOGGER.info("请求URL:{}", url);
        Request.Builder requestBuilder = new Request.Builder();
        if (headers != null) {
            requestBuilder.headers(headers);
        }

        Request okHttp3Request = requestBuilder.url(url).post(jsonBody).build();

        try {
            Response okHttpResponse = okHttpClient.newCall(okHttp3Request).execute();
            LOGGER.info("******** {} ********", "HTTP Response");
            respHeaders = okHttpResponse.headers();
            String responseInfo = okHttpResponse.toString();
            LOGGER.info(responseInfo);
            responseBuilder.append(okHttpResponse.body().string());
        } catch (IOException var11) {
            LOGGER.error("Exception happened during sending PostRequestWithJSONBody.", var11);
        }

        return responseBuilder.toString();
    }


    public static String sendSyncPostRequestWithFormBody(String subUri, JSONObject reqFormJSONObject) {
        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        Iterator var3 = reqFormJSONObject.entrySet().iterator();

        while(var3.hasNext()) {
            Entry entry = (Entry)var3.next();
            formBodyBuilder.add((String)entry.getKey(), entry.getValue().toString());
        }

        RequestBody formBody = formBodyBuilder.build();
        StringBuilder urlBuilder = new StringBuilder(host);
        String url = urlBuilder.append(subUri).toString();
        LOGGER.info("请求URL:{}", url);
        Request.Builder requestBuilder = new Request.Builder();
        if (headers != null) {
            requestBuilder.headers(headers);
        }

        Request okHttp3Request = requestBuilder.url(url).post(formBody).build();
        StringBuilder responseBuilder = new StringBuilder();
        try {
            Response okHttpResponse = okHttpClient.newCall(okHttp3Request).execute();
            LOGGER.info("******** {} ********", "HTTP Response");
            respHeaders = okHttpResponse.headers();
            String responseInfo = okHttpResponse.toString();
            LOGGER.info(responseInfo);
            responseBuilder.append(okHttpResponse.body().string());
        } catch (IOException var11) {
            LOGGER.error("Exception happened during sending PostRequestWithJSONBody.", var11);
        }
        return responseBuilder.toString();
    }

    public static Map getResponseHeaders(){
        if (respHeaders != null){
            Map respHeadersMap = new HashMap<>();
            for (String key : respHeaders.names()){
                respHeadersMap.put(key, respHeaders.get(key));
            }
            LOGGER.info("Response Headers 共有{}个。", respHeadersMap.size());
            LOGGER.info("Response Headers:{}", respHeaders.toString());
            return respHeadersMap;
        } else {
            LOGGER.warn("respHeaders is null.");
            return null;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy