作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想将 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/
我是一名优秀的程序员,十分优秀!