OkHttpsUtil

Posted killer-leon

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了OkHttpsUtil相关的知识,希望对你有一定的参考价值。

package club.tokenfans.bitdog.utils;

import java.io.IOException;
import java.security.KeyStore;
import java.util.Arrays;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.*;

import okhttp3.*;

/**
 * @ClassName OkHttpUtils.java
 * @Description 功能描述: 用于发送http请求
 * @author bitdog 2027年10月27日 下午5:13:01
 * @CopyRight bitdog
 */
public class OkHttpUtils 

    // 创建一个 OkHttpClient
    private static final OkHttpClient mOkHttpClient = getUnsafeOkHttpClient();

    // 参数格式
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    private static OkHttpClient getUnsafeOkHttpClient() 
        try 
            TrustManagerFactory trustManagerFactory = null;
            trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init((KeyStore)null);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
            if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) 
                throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
            
            X509TrustManager trustManager = (X509TrustManager)trustManagers[0];
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[] trustManager, null);
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS).connectionPool(new ConnectionPool(200, 5, TimeUnit.MINUTES))
                .sslSocketFactory(sslSocketFactory, trustManager).build();
            return okHttpClient;
         catch (Exception e) 
            throw new RuntimeException(e);
        
    

    /**
     * 方法描述:httpGet
     * 
     * @author bitdog 2019年5月10日 下午3:59:07
     * @param url
     *            serverHost可以带参数如http://www.baidu.com?param1=xxx&param2=xxx
     * @return
     * @throws IOException
     */
    public static String get(String url) throws IOException 
        Request request = new Request.Builder().url(url).get().build();
        Response response = mOkHttpClient.newCall(request).execute();
        return response.body().string();
    

    /**
     * 方法描述:httpGet
     * 
     * @author bitdog 2019年5月10日 下午3:53:50
     * @param url
     *            serverHost
     * @param params
     *            参数:map格式
     * @return
     * @throws IOException
     */
    public static String get(String url, Map<String, Object> params) throws IOException 
        // 构建请求参数
        StringBuffer paramSb = new StringBuffer();
        if (params != null) 
            for (Entry<String, Object> e : params.entrySet()) 

                if (e.getValue() != null) 
                    paramSb.append(e.getKey());
                    paramSb.append("=");
                    // 将参数值urlEncode编码,防止传递中乱码
                    paramSb.append(e.getValue().toString());
                    paramSb.append("&");
                
            
        
        if (paramSb.length() > 0) 
            String paramStr = paramSb.toString();
            paramStr = paramStr.substring(0, paramStr.length() - 1);
            url += "?" + paramStr;
        
        Request request = new Request.Builder().url(url).get().build();
        Response response = mOkHttpClient.newCall(request).execute();
        return response.body().string();
    

    /**
     * 方法描述:httpPost
     * 
     * @author bitdog 2019年5月10日 下午3:53:28
     * @param url
     *            serverHost
     * @param params
     *            参数:json格式
     * @return
     * @throws IOException
     */
    public static String post(String url, String params) throws IOException 
        RequestBody body = RequestBody.create(JSON, params);
        Request request = new Request.Builder().url(url).post(body).build();
        Response response = mOkHttpClient.newCall(request).execute();
        return response.body().string();
    

    /**
     * 方法描述:httpPost
     * 
     * @author bitdog 2019年5月10日 下午3:53:50
     * @param url
     *            serverHost
     * @param params
     *            参数:map格式
     * @return
     * @throws IOException
     */
    public static String post(String url, Map<String, Object> params) throws IOException 

        FormBody.Builder build = new FormBody.Builder();
        for (String key : params.keySet()) 
            if (params.get(key) != null) 
                build.add(key, params.get(key).toString());
            
        
        RequestBody body = build.build();
        Request request = new Request.Builder().url(url).post(body).build();
        Response response = mOkHttpClient.newCall(request).execute();
        return response.body().string();
    

    /**
     * 方法描述:httpPost
     *
     * @author bitdog 2019年5月10日 下午3:53:50
     * @param url
     *            serverHost
     * @param headers
     *            header头部添加参数
     * @param params
     *            参数:map格式
     * @return
     * @throws IOException
     */
    public static String post(String url, Map<String, Object> headers, Map<String, Object> params) throws IOException 

        // 封装请求参数
        FormBody.Builder build = new FormBody.Builder();
        for (String key : params.keySet()) 
            if (params.get(key) != null) 
                build.add(key, params.get(key).toString());
            
        
        RequestBody body = build.build();
        // 封装请求hearder头
        Request.Builder builder = new Request.Builder().url(url).post(body);
        if (headers != null && headers.size() > 0) 
            for (String headerKey : headers.keySet()) 
                builder.addHeader(headerKey, headers.get(headerKey).toString());
            
        

        Request request = builder.build();
        Response response = mOkHttpClient.newCall(request).execute();
        return response.body().string();
    

    /**
     * @Description 方法描述: httpPost
     * @author bitdog 2027年10月27日 下午5:10:13
     * @CopyRight
     * @param url
     * @param params
     * @param headers
     * @return
     * @throws IOException
     */
    public static String post(String url, String params, Map<String, Object> headers) throws IOException 
        RequestBody body = RequestBody.create(JSON, params);
        Request.Builder builder = new Request.Builder().url(url).post(body);
        // 添加http header
        if (headers != null && headers.size() > 0) 
            for (String headerKey : headers.keySet()) 
                builder.addHeader(headerKey, headers.get(headerKey).toString());
            
        
        Request request = builder.build();
        Response response = mOkHttpClient.newCall(request).execute();
        return response.body().string();
    

    /**
     * 方法描述:httpPut
     * 
     * @author bitdog 2019年5月10日 下午3:53:50
     * @param url
     *            serverHost
     * @param params
     *            参数:json格式
     * @return
     * @throws IOException
     */
    public static String put(String url, String params) throws IOException 
        RequestBody body = RequestBody.create(JSON, params);
        Request request = new Request.Builder().url(url).put(body).build();
        Response response = mOkHttpClient.newCall(request).execute();
        return response.body().string();
    

    /**
     * 方法描述:httpPut
     * 
     * @author bitdog 2019年5月10日 下午3:53:50
     * @param url
     *            serverHost
     * @param params
     *            参数:map格式数
     * @return
     * @throws IOException
     */
    public static String put(String url, Map<String, Object> params) throws IOException 
        FormBody.Builder build = new FormBody.Builder();
        for (String key : params.keySet()) 
            if (params.get(key) != null) 
                build.add(key, params.get(key).toString());
            
        
        RequestBody body = build.build();

        Request request = new Request.Builder().url(url).put(body).build();
        Response response = mOkHttpClient.newCall(request).execute();
        return response.body().string();
    

    /**
     * 方法描述:httpDelete
     * 
     * @author bitdog 2019年5月10日 下午3:53:50
     * @param url
     *            serverHost
     * @return
     * @throws IOException
     */
    public static String delete(String url) throws IOException 
        Request request = new Request.Builder().url(url).delete().build();
        Response response = mOkHttpClient.newCall(request).execute();
        return response.body().string();
    

    /**
     * 方法描述:httpPatch
     * 
     * @author bitdog 2019年5月10日 下午3:57:23
     * @param url
     *            serverHost
     * @param params
     *            参数:map格式
     * @return
     * @throws IOException
     */
    public static String patch(String url, Map<String, Object> params) throws IOException 
        FormBody.Builder build = new FormBody.Builder();
        for (String key : params.keySet()) 
            if (params.get(key) != null) 
                build.add(key, params.get(key).toString());
            
        
        RequestBody body = build.build();
        Request request = new Request.Builder().url(url).patch(body).build();
        Response response = mOkHttpClient.newCall(request).execute();
        return response.body().string();
    

    /**
     * 方法描述:httpPatch
     * 
     * @author bitdog 2019年5月10日 下午3:57:23
     * @param url
     *            serverHost
     * @param params
     *            参数:json格式
     * @return
     * @throws IOException
     */
    public static String patch(String url, String params) throws IOException 
        RequestBody body = RequestBody.create(JSON, params);
        Request request = new Request.Builder().url(url).patch(body).build();
        Response response = mOkHttpClient.newCall(request).execute();
        return response.body().string();
    

    /**
     * 方法描述:httpHead
     * 
     * @author bitdog 2019年5月10日 下午3:58:28
     * @param url
     *            serverHost
     * @return
     * @throws IOException
     */

    public static String head(String url) throws IOException 
        Request request = new Request.Builder().url(url).head().build();
        Response response = mOkHttpClient.newCall(request).execute();
        return response.body().string();
    

    /**
     * 方法描述:httpGet
     *
     * @author bitdog 2019年5月10日 下午3:59:07
     * @param url
     *            serverHost可以带参数如http://www.baidu.com?param1=xxx&param2=xxx
     * @return
     * @throws IOException
     */
    public static String getWithHeaders(String url, Map<String, Object> headers) throws IOException 
        Request.Builder builder = new Request.Builder().url(url).get();
        if (headers != null && headers.size() > 0) 
            for (String headerKey : headers.keySet()) 
                builder.addHeader(headerKey, headers.get(headerKey).toString());
            
        
        Request request = builder.build();
        Response response = mOkHttpClient.newCall(request).execute();
        return response.body().string();
    

    /**
     * get
     * 
     * @param url
     * @param headers
     * @param params
     * @return java.lang.String
     * @author bitdog 2022/5/11 17:56
     */
    public static String get(String url, Map<String, Object> headers, Map<String, Object> params) throws IOException 

        // 构建请求参数
        StringBuffer paramSb = new StringBuffer();
        if (params != null) 
            for (Entry<String, Object> e : params.entrySet()) 

                if (e.getValue() != null) 
                    paramSb.append(e.getKey());
                    paramSb.append("=");
                    // 将参数值urlEncode编码,防止传递中乱码
                    paramSb.append(e.getValue().toString());
                    paramSb.append("&");
                
            
        
        if (paramSb.length() > 0) 
            String paramStr = paramSb.toString();
            paramStr = paramStr.substring(0, paramStr.length() - 1);
            url += "?" + paramStr;
        

        Request.Builder builder = new Request.Builder().url(url).get();
        if (headers != null && headers.size() > 0) 
            for (String headerKey : headers.keySet()) 
                builder.addHeader(headerKey, headers.get(headerKey).toString());
            
        
        Request request = builder.build();
        Response response = mOkHttpClient.newCall(request).execute();

        return response.body().string();
    

    public static Response postResponse(String url, Map<String, Object> headers, Map<String, Object> params)
        throws IOException 

        // 封装请求参数
        FormBody.Builder build = new FormBody.Builder();
        for (String key : params.keySet()) 
            if (params.get(key) != null) 
                build.add(key, params.get(key).toString());
            
        
        RequestBody body = build.build();
        // 封装请求hearder头
        Request.Builder builder = new Request.Builder().url(url).post(body);
        if (headers != null && headers.size() > 0) 
            for (String headerKey : headers.keySet()) 
                builder.addHeader(headerKey, headers.get(headerKey).toString());
            
        

        Request request = builder.build();
        return mOkHttpClient.newCall(request).execute();
    

以上是关于OkHttpsUtil的主要内容,如果未能解决你的问题,请参考以下文章

OkHttpsUtil