gpt4 book ai didi

java - 如何从 HttpURLConnection 创建 ResponseEntity?

转载 作者:行者123 更新时间:2023-11-30 07:13:53 25 4
gpt4 key购买 nike

我想将 HttpURLConnection 的响应检索到 ResponseEntity 中。我收到 406 错误。

提前谢谢您。

@RequestMapping(value = "/retrive", method = { RequestMethod.GET })
public ResponseEntity<?> retrive (HttpServletRequest request){
//1. call a rest by rest client
URL u = new URL("http://localhost:8080/getHello");
HttpURLConnection uc = (HttpURLConnection) u.openConnection();

//2, create HttpHeaders for ResponseEntity
HttpHeaders responseHeaders = new HttpHeaders();
for (int i = 0;; i++) {
String headerName = uc.getHeaderFieldKey(i);
String headerValue = uc.getHeaderField(i);
if(headerName != null && headerValue != null){
responseHeaders.set(headerName, headerValue);
}
if (headerName == null && headerValue == null) {
break;
}
}
//3. create ResponseEntity
InputStream inputStream = uc.getInputStream();
return new ResponseEntity<>(inputStream, responseHeaders, HttpStatus.OK);
}

最佳答案

假设您正在尝试构建某种反向代理,那么您只需从输入流复制到输出流即可:

  @RequestMapping(value = "/retrive", method = { RequestMethod.GET })
public ResponseEntity<?> retrive (HttpServletRequest request, HttpServletResponse response){
//1. call a rest by rest client
URL u = new URL("http://localhost:8080/getHello");
HttpURLConnection uc = (HttpURLConnection) u.openConnection();

//2, create HttpHeaders for ResponseEntity
HttpHeaders responseHeaders = new HttpHeaders();
for (int i = 0;; i++) {
String headerName = uc.getHeaderFieldKey(i);
String headerValue = uc.getHeaderField(i);
if(headerName != null && headerValue != null){
responseHeaders.set(headerName, headerValue);
}
if (headerName == null && headerValue == null) {
break;
}
}

try (InputStream inputStream = uc.getInputStream();
OutputStream outputStream = response.getOutputStream();
)
{
IOUtils.copy(inputStream, outputStream);
}
//3. create ResponseEntity
return new ResponseEntity<>(responseHeaders, HttpStatus.OK);
}

关于java - 如何从 HttpURLConnection 创建 ResponseEntity?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38747421/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com