我想将响应从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/