spring-mvc – spring mvc http proxy

我想编写一个
spring MVC Controller类,它只接受输入中的任何http请求,向其添加基本身份验证标头并将此请求转发给另一台服务器.

我尝试这样的事情没有成功.

    @Controller
    @RequestMapping("/proxyws")
    public class ProxyController {

    @RequestMapping("/**")
    @ResponseBody
    public String mirrorRest( @RequestBody String body, HttpMethod method, HttpServletRequest request, HttpServletResponse response) throws URISyntaxException
    {

        String server = "localhost";
        int port = 8080;
        URI uri = new URI("http", null, server, port, request.getRequestURI(), request.getQueryString(), null);
        RestTemplate restTemplate=new RestTemplate();
        HttpEntity entity = new HttpEntity<String>(body);
        String plainCreds = "APP_CLIENT:APP_PASSWORD"; 
        byte[] plainCredsBytes = plainCreds.getBytes();
        byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
        String base64Creds = new String(base64CredsBytes);
        entity.getHeaders().add("Authorization", "Basic " + base64Creds);

        ResponseEntity<String> responseEntity = restTemplate.exchange(uri, method, entity, String.class);

        return responseEntity.getBody();
    }

对于输入中的GET方法,我得到以下异常:
org.springframework.http.converter.HttpMessageNotReadableException:缺少必需的请求正文内容:

org.springframework.web.method.HandlerMethod$HandlerMethodParameter@8051792a
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleEmptyBody(RequestResponseBodyMethodProcessor.java:189)
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:170)
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:105)

对于POST请求,我在使用le basic auth头时遇到了其他麻烦:

java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableMap.put(Collections.java:1342)
at org.springframework.http.HttpHeaders.add(HttpHeaders.java:831)

Thanx为您提供帮助!

最佳答案 实例化后,您无法修改HttpEntity对象的标头.您需要通过不同的HttpEntity构造函数传递标题,例如

public HttpEntity(T body, MultiValueMap<String, String> headers) {
    this.body = body;
    HttpHeaders tempHeaders = new HttpHeaders();
    if (headers != null) {
        tempHeaders.putAll(headers);
    }
    this.headers = HttpHeaders.readOnlyHttpHeaders(tempHeaders);
}

请注意this.headers的初始化:这是创建只读副本的地方.

点赞