zoukankan      html  css  js  c++  java
  • 实现java非阻塞http请求的两种方式

    1.okhttp

    public void okhttp() {
        Request request = new Request.Builder()
            .url()
            .post(RequestBody.create(MediaType.parse("application/json"), content))
            .build();
    
          OkHttpClient client = new OkHttpClient.Builder()
              .connectionPool(new ConnectionPool(50, 5, TimeUnit.MINUTES))
              .readTimeout(5, TimeUnit.SECONDS)
              .connectTimeout(5, TimeUnit.SECONDS)
              .build();
    
          client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
              log.info("error:" + e.toString());
            }
    
            @Override
            public void onResponse(Call call, Response response) throws IOException {
              log.info("success:" + response.body().string());
            }
          });
      }

    2.webClient

    public static Mono<String> webClient(){
            ReactorClientHttpConnector connector = new ReactorClientHttpConnector(
                    options -> options.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
                            .compression(true)
                            .afterNettyContextInit(ctx -> {
                                ctx.addHandlerLast(new ReadTimeoutHandler(3000, TimeUnit.MILLISECONDS));
                            }));
    
            WebClient client = WebClient.builder()
                        .defaultHeader(HttpHeaders.CONTENT_TYPE, API_MIME_TYPE)
                        .defaultHeader(HttpHeaders.USER_AGENT, USER_AGENT)
                        .clientConnector(connector)
                        .build();
         return client.get()
                    .uri()
                    .retrieve()
                    .bodyToMono(String.class)
                    .doOnError(e -> logger.info("error:" + e))
                    .doOnSuccess(result -> logger.info("result" + result));
        }
  • 相关阅读:
    npx vs npm
    RubyGem镜像/ruby国内镜像
    IOS开发依赖管理工具CocoaPods
    alpine linux
    阿里妈妈图标库
    java应用系统运行速度慢的解决方法
    jvm程序执行慢诊断手册
    js强制不使用“兼容性视图”
    java.lang.NumberFormatException: Infinite or NaN
    ALTER添加列后,立即UPDATE该列会报错
  • 原文地址:https://www.cnblogs.com/zhh2020/p/13415359.html
Copyright © 2011-2022 走看看