背景
之前在spring上面使用过okhttp:
Component
package com.zyl.config;import okhttp3.ConnectionPool;import okhttp3.Credentials;import okhttp3.OkHttpClient;import okhttp3.logging.HttpLoggingInterceptor;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.stereotype.Component;import java.util.concurrent.TimeUnit;/** okhttp3 configuration */@Componentpublic class OkHttpConfiguration { private Logger logger = LoggerFactory.getLogger(OkHttpConfiguration.class); /** * 为新连接设置默认连接超时,单位毫秒 */ @Value("${connectTimeout:10000}") private long connectTimeout; /** * true表示启用连接池,false表示不启用连接池 */ @Value("${connectionPoolEnable:true}") private boolean connectionPoolEnable; /** * sap的基本认证 */ @Value("${username:zyl}") private String username; /** * sap的基本认证 */ @Value("${password:xxxyyy}") private String password; @Bean public OkHttpClient okHttpClient(){ OkHttpClient.Builder builder = new OkHttpClient.Builder();if (connectionPoolEnable){ builder.connectionPool(new ConnectionPool()); } builder.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS); builder.authenticator((route, response) -> { if (response.request().header("Authorization") != null) { return null; // Give up, we've already attempted to authenticate. } logger.info("Authenticating for response: " + response); logger.info("Challenges: " + response.challenges()); String credential = Credentials.basic(username, password); return response.request().newBuilder() .header("Authorization", credential) .build(); }); HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BASIC); builder.addInterceptor(logging); return builder.build(); }}
运行时配置中心,现在还玩不6。
Controller
@Autowiredprivate OkHttpClient okHttpClient;
在控制器中使用:
Request request = new Request.Builder() .url("https://www.google.com/ncr") .addHeader("myheader", "hello header") .get() .build();Response response = null;try { response = okhttpClient.newCall(request).execute(); response.body().string();} catch (IOException e) { e.printStackTrace();} finally { if(response != null) { response.close(); }}