SpingBoot 使用okHttp发application/x-www-form-urlencoded类型的请求

1.maven配置

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

2.okhttp配置类,按需设置参数

@Slf4j
@Configuration
public class OkHttpConfig {

    /**
     * 保持连接时间
     */
    private static final long KEEP_ALIVE_TIME = 5000L;

    private static final long TIMEOUT = 60000L;

    @Bean
    public OkHttpClient okHttpClient() {
        ConnectionPool connectionPool = new ConnectionPool(32, KEEP_ALIVE_TIME, TimeUnit.MILLISECONDS);

        return new OkHttpClient().newBuilder()
                .connectTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
                .writeTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
                .readTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
                .connectionPool(connectionPool)
                .retryOnConnectionFailure(false)
                .build();
    }
}

3.发送请求

public String post(String url) {
      RequestBody body = new FormBody.Builder()
              .add("timestamp", new Date())
              .build();

      Request request = new Request.Builder()
              .url(url)
              .post(body)
              .build();
      try (Response response = okHttpClient.newCall(request).execute()) {
          return response.body().string();
      } catch (SocketTimeoutException e) {
          log.error("[OkHttpClientUtils#post] 请求超时。e=", e);
          throw new RuntimeException("Okhttp timeout.");
      } catch (Exception e) {
          log.error("[OkHttpClientUtils#post] 请求异常。 e=", e);
          return null;
      }
  }
posted @ 2022-09-30 15:06  237237  阅读(3295)  评论(0)    收藏  举报