OkHttp配置Basic Auth

厉念
2023-12-01

需求:远程服务使用HTTPS连接,并需要Basic Auth认证

在配置类里面注入一个自定义OkHttpClient


    @Value("${sign.httpName}")
    private String rtspName;
    @Value("${sign.httpPwd}")
    private String rtspPwd;
    
    @Bean
    public OkHttpClient buildBasicAuthClient() {
        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) {

            }

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

            }

            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };
        SSLSocketFactory sslSocketFactory = null;
        try {
            SSLContext sslContext;
            sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, new X509TrustManager[]{trustManager}, null);
            sslSocketFactory = sslContext.getSocketFactory();
        } catch (GeneralSecurityException e) {
            throw new RuntimeException(e);
        }
    
        return new OkHttpClient.Builder().authenticator(new Authenticator() {
            @Override
            public Request authenticate(Route route, Response response) throws IOException {
                String credential = Credentials.basic(rtspName, rtspPwd);
                return response.request().newBuilder().header("Authorization", credential).build();
            }
        })
        .connectTimeout(10, TimeUnit.SECONDS)
        //忽略SSL
        .sslSocketFactory(sslSocketFactory, trustManager)
        .hostnameVerifier(new SSLSocketClient().getHostnameVerifier())
        .build();
    }

使用

    @Autowired
    private OkHttpClient okHttpClient;
    @Value("${sign.rtspserverUrl}")
    private String rtspserverUrl;

    /**
     * 获取分组列表
     *
     * @return
     * @throws Exception
     */
    public Rest<List<CameraGroupDto>> getGroup() throws Exception {
        Request request = new Request.Builder()
                .url(rtspserverUrl + "group/list")
                .get()
                .build();
        Response response = okHttpClient.newCall(request).execute();
        assert response.body() != null;
        String groupStr = response.body().string();
        if(StrUtil.isNotEmpty(groupStr)){
            List<CameraGroupDto> groupDtoList = JSONArray.parseArray(groupStr,CameraGroupDto.class);
            return Rest.success(groupDtoList);
        }
        return Rest.fail(ExceptionEnum.NOT_FOUND);
    }
 类似资料: