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

org.iartisan.runtime.utils.HttpRequestUtil Maven / Gradle / Ivy

The newest version!
package org.iartisan.runtime.utils;


import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.rmi.RemoteException;
import java.util.Map;

/**
 * http request util class
 *
 * @author King  2018/11/10
 */
public class HttpRequestUtil {

    public static Logger logger = LoggerFactory.getLogger(HttpRequestUtil.class);
    private static OkHttpClient client = null;

    static {
        try {
            client = new OkHttpClient.Builder()
                    .sslSocketFactory(SSLUtil.getSSLSocketFactory(), SSLUtil.getTrustManager())
                    .hostnameVerifier(SSLUtil.getHostnameVerifier()).build();
        } catch (Exception e) {
            logger.error("Exception:", e);
        }
    }

    public static Response sendPost(String url, String data, Map headers) throws RemoteException {
        Request.Builder builder = new Request.Builder();
        //添加头部请求
        if (null != headers && !headers.isEmpty()) {
            headers.forEach((k, v) ->
                    builder.addHeader(k, v)
            );
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), data);
        try {
            Request request = builder.url(url).post(requestBody).build();
            okhttp3.Response response = client.newCall(request).execute();
            return response;
        } catch (IOException e) {
            logger.error("send IOException:", e);
            throw new RemoteException(e.getMessage());
        } catch (Exception e) {
            logger.error("send Exception:", e);
            throw new RemoteException(e.getMessage());
        }
    }

    public static Response sendPost(String url, String data) throws RemoteException {
        return sendPost(url, data, null);
    }

    public static String sendGet(String url, Map headers) throws RemoteException {
        Request.Builder builder = new Request.Builder();
        //添加头部请求
        if (null != headers && !headers.isEmpty()) {
            headers.forEach((k, v) ->
                    builder.addHeader(k, v)
            );
        }
        Request request = builder.url(url).build();
        try {
            Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (Exception e) {
            logger.error("send Exception:", e);
            throw new RemoteException(e.getMessage());
        }
    }

    public static String sendGet(String url) throws RemoteException {
        return sendGet(url, null);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy