spring註解配置okhttp3

背景

之前在spring上面使用過okhttp:spring傳統xml配置okhttp3

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 */
@Component
public 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

@Autowired
private 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();
  }
}

參考

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章