OkHttp3的使用

1,305 阅读1分钟

1.依赖引入

    <dependency>
      <groupId>com.squareup.okhttp3</groupId>
      <artifactId>okhttp</artifactId>
    </dependency>

2.配置文件okhttp.properties的属性配置

okhttp.readTimeout=xxxx
okhttp.writeTimeout=xxxx
okhttp.connectTimeout=xxxx
okhttp.retryOnConnectionFailure=true

3.配置类

@Setter
@Getter
@Component
@PropertySource(value = "classpath:okhttp.properties")
@ConfigurationProperties(prefix = "okhttp")
public class OkHttpSettings {

  private long readTimeout;
  private long writeTimeout;
  private long connectTimeout;
  private boolean retryOnConnectionFailure;
}
@Configuration
public class OkHttpConfig {

  @Autowired
  private OkHttpSettings okHttpSettings;

  @Bean("okHttpClient")
  public OkHttpClient okHttpClient() {
    return new OkHttpClient.Builder()
      .retryOnConnectionFailure(okHttpSettings.isRetryOnConnectionFailure())
      .connectTimeout(okHttpSettings.getConnectTimeout(), TimeUnit.MILLISECONDS)
      .writeTimeout(okHttpSettings.getWriteTimeout(), TimeUnit.MILLISECONDS)
      .readTimeout(okHttpSettings.getReadTimeout(), TimeUnit.MILLISECONDS)
      .build();
  }
}

4.使用OKhttp3调用接口

private byte[] getBytes(String url) {
    Request request = new Request.Builder()
      .url(url).build();

    try (Response response = okHttpClient.newCall(request).execute()) {
      ResponseBody body = response.body();
      if (!response.isSuccessful() || Objects.isNull(body)) {
        return null;
      }

      return body.bytes();
    } catch (IOException e) {
      log.error("url is {},error is {}", url,e.getMessage());
    }

    return null;
  }