Okhttp将响应转换为Spring ResponseEntity

问题描述 投票:0回答:1

我有一个带有POST REST API的Springboot 2.2 Web服务。我正在使用Okhttp客户端向第三方服务发出请求。我想将第三方服务的确切响应返回给我的Web服务的调用者。okhttp的所有食谱均参考:

 if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

      System.out.println(response.body().string());

我尝试在我的api中返回okhttp响应,但我仅返回到调用者示例:

{
    "redirect": false,
    "successful": true
} 

因此它不会插入从第三方服务返回的消息。

有人知道如何将Okhttp响应对象转换为Spring ResponseEntity对象,以便我可以返回http响应代码和消息

java spring-boot httpresponse okhttp
1个回答
0
投票

在这种情况下,您可以直接在Spring-Webservice中使用HttpServletResponse,并将okhttp ResponseBody给定的InputStream通过管道传递到HttpServletResponse的OutputStream。

@PostMapping(path="/my/webservice")
public void postSomething(HttpServletResponse response){
   okhttp3.Response redirectedResponse = redirectCall();
   if(redirectedResponse.isSuccessful())
     pipe(response.getOutputStream(), redirectedResponse.body.byteStream());
}
© www.soinside.com 2019 - 2024. All rights reserved.