首頁 > 軟體

Java中的OkHttp使用教學

2022-04-16 13:01:02

什麼是OKHttp

一般在Java平臺上,我們會使用Apache HttpClient作為Http使用者端,用於傳送 HTTP 請求,並對響應進行處理。比如可以使用http使用者端與第三方服務(如SSO服務)進行整合,當然還可以爬取網上的資料等。OKHttp與HttpClient類似,也是一個Http使用者端,提供了對 HTTP/2 和 SPDY 的支援,並提供了連線池,GZIP 壓縮和 HTTP 響應快取功能;

OkHttp是目前非常火的網路庫,它有以下特性:

1.支援HTTP/2,允許所有同一個主機地址的請求共用同一個socket連線

2.連線池減少請求延時

3.透明的GZIP壓縮減少響應資料的大小

4.快取響應內容,避免一些完全重複的請求

OkHttp基本使用

  • OkHttpClient:使用者端物件
  • Request:存取請求,Post請求中需要包含RequestBody
  • RequestBody:請求資料,在Post請求中用到
  • Response:即網路請求的響應結果
  • MediaType:資料型別,用來表明資料是json,image,pdf等一系列格式
  • client.newCall(request).execute():同步的請求方法
  • client.newCall(request).enqueue(Callback callBack):非同步的請求方法,但Callback是執行在子執行緒中的,因此不能在此進行UI更新操作

官網:http://square.github.io/okhttp/

新增依賴

 <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.10.0</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.60</version>
        </dependency>

OkHttp工具類

package com.loginsimpl.utils;

import com.alibaba.fastjson.JSON;
import okhttp3.*;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class OkHttpUtils {
    private static volatile OkHttpClient okHttpClient = null;
    private static volatile Semaphore semaphore = null;
    private Map<String, String> headerMap;
    private Map<String, String> paramMap;
    private String url;
    private Request.Builder request;

    /**
     * 初始化okHttpClient,並且允許https存取
     */
    private OkHttpUtils() {
        if (okHttpClient == null) {
            synchronized (OkHttpUtils.class) {
                if (okHttpClient == null) {
                    TrustManager[] trustManagers = buildTrustManagers();
                    okHttpClient = new OkHttpClient.Builder()
                            .connectTimeout(15, TimeUnit.SECONDS)
                            .writeTimeout(20, TimeUnit.SECONDS)
                            .readTimeout(20, TimeUnit.SECONDS)
                            .sslSocketFactory(createSSLSocketFactory(trustManagers), (X509TrustManager) trustManagers[0])
                            .hostnameVerifier((hostName, session) -> true)
                            .retryOnConnectionFailure(true)
                            .build();
                    addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
                }
            }
        }
    }

    /**
     * 用於非同步請求時,控制存取執行緒數,返回結果
     *
     * @return
     */
    private static Semaphore getSemaphoreInstance() {
        //只能1個執行緒同時存取
        synchronized (OkHttpUtils.class) {
            if (semaphore == null) {
                semaphore = new Semaphore(0);
            }
        }
        return semaphore;
    }

    /**
     * 建立OkHttpUtils
     *
     * @return
     */
    public static OkHttpUtils builder() {
        return new OkHttpUtils();
    }

    /**
     * 新增url
     *
     * @param url
     * @return
     */
    public OkHttpUtils url(String url) {
        this.url = url;
        return this;
    }

    /**
     * 新增引數
     *
     * @param key   引數名
     * @param value 引數值
     * @return
     */
    public OkHttpUtils addParam(String key, String value) {
        if (paramMap == null) {
            paramMap = new LinkedHashMap<>(16);
        }
        paramMap.put(key, value);
        return this;
    }

    /**
     * 新增請求頭
     *
     * @param key   引數名
     * @param value 引數值
     * @return
     */
    public OkHttpUtils addHeader(String key, String value) {
        if (headerMap == null) {
            headerMap = new LinkedHashMap<>(16);
        }
        headerMap.put(key, value);
        return this;
    }

    /**
     * 初始化get方法
     *
     * @return
     */
    public OkHttpUtils get() {
        request = new Request.Builder().get();
        StringBuilder urlBuilder = new StringBuilder(url);
        if (paramMap != null) {
            urlBuilder.append("?");
            try {
                for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                    urlBuilder.append(URLEncoder.encode(entry.getKey(), "utf-8")).
                            append("=").
                            append(URLEncoder.encode(entry.getValue(), "utf-8")).
                            append("&");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            urlBuilder.deleteCharAt(urlBuilder.length() - 1);
        }
        request.url(urlBuilder.toString());
        return this;
    }

    /**
     * 初始化post方法
     *
     * @param isJsonPost true等於json的方式提交資料,類似postman裡post方法的raw
     *                   false等於普通的表單提交
     * @return
     */
    public OkHttpUtils post(boolean isJsonPost) {
        RequestBody requestBody;
        if (isJsonPost) {
            String json = "";
            if (paramMap != null) {
                json = JSON.toJSONString(paramMap);
            }
            requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        } else {
            FormBody.Builder formBody = new FormBody.Builder();
            if (paramMap != null) {
                paramMap.forEach(formBody::add);
            }
            requestBody = formBody.build();
        }
        request = new Request.Builder().post(requestBody).url(url);
        return this;
    }

    /**
     * 同步請求
     *
     * @return
     */
    public String sync() {
        setHeader(request);
        try {
            Response response = okHttpClient.newCall(request.build()).execute();
            assert response.body() != null;
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
            return "請求失敗:" + e.getMessage();
        }
    }

    /**
     * 非同步請求,有返回值  (限流的,同一時間只允許一個存取,其他等待)
     */
    public String async() {
        StringBuilder buffer = new StringBuilder("");
        setHeader(request);
        okHttpClient.newCall(request.build()).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                buffer.append("請求出錯:").append(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                assert response.body() != null;
                buffer.append(response.body().string());
                getSemaphoreInstance().release();
            }
        });
        try {
            getSemaphoreInstance().acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

    /**
     * 非同步請求,帶有介面回撥
     *
     * @param callBack
     */
    public void async(ICallBack callBack) {
        setHeader(request);
        okHttpClient.newCall(request.build()).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callBack.onFailure(call, e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                assert response.body() != null;
                callBack.onSuccessful(call, response.body().string());
            }
        });
    }

    /**
     * 為request新增請求頭
     *
     * @param request
     */
    private void setHeader(Request.Builder request) {
        if (headerMap != null) {
            try {
                for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                    request.addHeader(entry.getKey(), entry.getValue());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 生成安全通訊端工廠,用於https請求的證書跳過
     *
     * @return
     */
    private static SSLSocketFactory createSSLSocketFactory(TrustManager[] trustAllCerts) {
        SSLSocketFactory ssfFactory = null;
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new SecureRandom());
            ssfFactory = sc.getSocketFactory();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ssfFactory;
    }

    private static TrustManager[] buildTrustManagers() {
        return new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                    }

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

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };
    }

    /**
     * 自定義一個介面回撥
     */
    public interface ICallBack {

        void onSuccessful(Call call, String data);

        void onFailure(Call call, String errorMsg);

    }
}


使用案例

傳送get請求

        String sync = OkHttpUtils.builder().url("http://localhost:9100/user/all")
                .addHeader("token", "xxxxxxx")
                .addParam("name", "xxx").addParam("pass", "xxx")
                .get()
                .sync();
        System.out.println(sync);

傳送Post請求

        String sync = OkHttpUtils.builder().url("http://localhost:9100/user/all")
                .addHeader("token", "xxxxxxx")
                .addParam("name", "xxx").addParam("pass", "xxx")
                .post(true) // true 為json提交方式
                .sync();
        System.out.println(sync);

傳送非同步請求

需要實現ICallBack介面

//回撥實現類
public class AsyncHttpServiceImpl implements OkHttpUtils.ICallBack {
    @Override
    public void onSuccessful(Call call, String data) {
        //介面正常返回的內容
        System.out.println("onSuccessful"+data);

    }

    @Override
    public void onFailure(Call call, String errorMsg) {
        //介面錯誤返回的內容
        System.out.println("onFailure"+errorMsg);
    }
}

傳送非同步請求

       OkHttpUtils.builder().url("http://localhost:9100/user/all")
                .addHeader("token", "xxxxxxx")
                .addParam("name", "xxx").addParam("pass", "xxx")
                .post(true)
                .async(new AsyncHttpServiceImpl());

到此這篇關於Java-OkHttp使用教學的文章就介紹到這了,更多相關Java-OkHttp使用內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com