簡體   English   中英

RestTemplate:如何獲取原始響應

[英]RestTemplate: How to get the raw response

我正在使用 RestTemplate 訪問服務。

RestTemplate rt = new RestTemplate ();
HttpEntity <String> he = new HttpEntity <String> (output, hh);
ResponseEntity <String> re = rt.exchange ("http://localhost:8080/my", HttpMethod.GET, he, String.class);

ResponseEntity具有用於訪問響應的getBodygetHeaders getHeaders已經是標題行的解析列表。

有沒有辦法可以將原始響應作為一大堆字節獲得?

為此,您將使用以下execute方法簽名:

   execute(URI url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor)

此方法將對給定 URL 執行 HTTP 方法,使用 RequestCallback 准備請求,並使用 ResponseExtractor 讀取響應。

下一步是為ResponseExtractor接口編寫一個自定義實現並覆蓋負責從響應中提取數據的extractData()

這是示例。 首先,在控制器類中編寫一些虛擬方法,如下所示:

@PostMapping(value = "/hello")
public String test() {
    return "Hello world";
}

然后,編寫將使用restTemplate調用上述方法並將響應作為字節數組返回的方法:

 @GetMapping("/test")
    public void test() throws IOException {
        final URI url = URI.create("http://localhost:8080/hello");
        final Map<String, String> headers = new HashMap<>();
        headers.put("Accept", "application/json");
        // Here you can set headers, request body,query parans,ect..
        RequestCallback requestCallback = r -> {
            //example: r.getBody().write(("username=" + username).getBytes());
            r.getHeaders().setAll(headers);
        };
        byte[] res = restTemplate.execute(url, HttpMethod.POST, requestCallback, new ResponseExtractor<byte[]>() {

            @Override
            public byte[] extractData(ClientHttpResponse response) throws IOException {
                byte[] data = new byte[1024];
                // return data from response as byte array
                response.getBody().read(data);
                return data;
            }
        });
        //write result in console
        ByteArrayInputStream byteArrayInputStr
                = new ByteArrayInputStream(res);
        int b = 0;
        while ((b = byteArrayInputStr.read()) != -1) {
            char ch = (char) b;
            System.out.println("Char : " + ch);
        }

    }

如果您執行test()方法,您應該會看到如下輸出:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM