如何在发送请求后编辑方法

How to edit method after sent request

我想从网站获取四个值,但每一步都需要编辑参数。我以为我可以和遗嘱执行人一起做,但我做不到。那么,如何在发送前编辑每个 CompletableFuture 中的参数?

        HttpRequest httpRequest = HttpRequest.newBuilder()
            .version(Version.HTTP_1_1)
            .uri(URI.create(sourceUrl))
            .header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
            .method("POST", BodyPublishers.ofFile(Paths.get("Resources/Payload.txt")))
            .build();

        ExecutorService executorService = Executors.newFixedThreadPool(4);

        HttpClient httpClient = HttpClient.newBuilder()
            .executor(executorService)
            .connectTimeout(Duration.ofSeconds(10))
            .build();

        CompletableFuture<HttpResponse<String>> a = 
            httpClient.sendAsync(httpRequest, BodyHandlers.ofString());

        CompletableFuture<HttpResponse<String>> b = 
            httpClient.sendAsync(httpRequest, BodyHandlers.ofString());

        CompletableFuture<HttpResponse<String>> c = 
            httpClient.sendAsync(httpRequest, BodyHandlers.ofString());

        CompletableFuture<HttpResponse<String>> d = 
            httpClient.sendAsync(httpRequest, BodyHandlers.ofString());
    }

HttpRequest 是有状态的,这意味着一个实例不能代表多个请求。

您必须为每个请求创建一个新实例。

只需使用 HttpRequest.Builder 并让它构建两个交替实例。
一般来说,调用.build()一次,配置就完成了。
例如。添加一个采用 string 的方法,然后是 HttpRequest
的 returns 实例 ...基本意图是减少重复代码。