spring註解配置okhttp3

背景

以前在spring上面使用過okhttp:spring傳統xml配置okhttp3java

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。git

Controller

@Autowired
private OkHttpClient okHttpClient;

在控制器中使用:github

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

參考

相關文章
相關標籤/搜索