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

参考

转载于:https://my.oschina.net/fxtxz2/blog/2985877

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值