public CompletableFuture send()

in dubbo-remoting-extensions/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/restclient/OKHttpRestClient.java [50:126]


    public CompletableFuture<RestResult> send(RequestTemplate requestTemplate) {

        Request.Builder builder = new Request.Builder();
        // url
        builder.url(requestTemplate.getURL());

        Map<String, Collection<String>> allHeaders = requestTemplate.getAllHeaders();

        boolean hasBody = false;
        RequestBody requestBody = null;
        // GET & HEAD body is forbidden
        if (HttpMethod.permitsRequestBody(requestTemplate.getHttpMethod())) {
            requestBody = RequestBody.create(null, requestTemplate.getSerializedBody());
            hasBody = true;
        }

        // header
        for (String headerName : allHeaders.keySet()) {
            Collection<String> headerValues = allHeaders.get(headerName);
            if (!hasBody && "Content-Length".equals(headerName)) {
                continue;
            }
            for (String headerValue : headerValues) {

                builder.addHeader(headerName, headerValue);
            }
        }

        builder.method(requestTemplate.getHttpMethod(), requestBody);

        CompletableFuture<RestResult> future = new CompletableFuture<>();

        okHttpClient.newCall(builder.build()).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                future.completeExceptionally(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                future.complete(new RestResult() {
                    @Override
                    public String getContentType() {
                        return response.header("Content-Type");
                    }

                    @Override
                    public byte[] getBody() throws IOException {
                        ResponseBody body = response.body();
                        return body == null ? null : body.bytes();
                    }

                    @Override
                    public Map<String, List<String>> headers() {
                        return response.headers().toMultimap();
                    }

                    @Override
                    public byte[] getErrorResponse() throws IOException {
                        return getBody();
                    }

                    @Override
                    public int getResponseCode() throws IOException {
                        return response.code();
                    }

                    @Override
                    public String getMessage() throws IOException {
                        return appendErrorMessage(response.message(), new String(getBody()));
                    }
                });
            }
        });

        return future;
    }