将POST从一个API转发到另一个API时出现错误代码415

时间:2019-03-04 11:39:27

标签: java rest spring-boot post

我正在从邮递员客户端向Java API发送一个application / json类型,该Java API将所有请求转发到该情况下的特定API。 在这种具体情况下,我有一个登录API,我想让中心代码听到此JSON:

邮递员的JSON

{
    "name": "random name",
    "password": "random passwd"
}

执行转发的API

@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String redirectHttpRequest(HttpServletRequest request, @Value("${endpoint}") String newURL,
        HttpServletResponse response) throws IOException {

    try {

        RestTemplate restTemplate = new RestTemplate();
        String result = null;


        String body = IOUtils.toString(request.getReader());

        if (request.getMethod().equals("GET")) {
            // result = restTemplate.getForObject(redirectUrl.toString(), String.class);
        } else if (request.getMethod().equals("POST")) {
            result = restTemplate.postForObject(newURL, body, String.class);

        }
        return result;

    } catch (HttpClientErrorException e) {
        System.out.println(e);
        return "OLA";
    }

}

该新URL是另一个API的URL(在这种情况下,它是localhost:8080,来自application.properties文件)。

enter image description here

我已经通过邮递员测试了登录API,并且可以正常工作,但是当我尝试将其连接到该转发API时,出现以下错误:

  

org.springframework.web.client.HttpClientErrorException:415空。

我想知道我在做错什么或做这件事的另一种方式。

邮递员通话 enter image description here

第二终结点代码 enter image description here

传递给第二个端点的正文的值 enter image description here

用户类别

公共类用户{

private String name;

private String password;

private List<String> groups;

public User(String name, String password) {
    this.name = name;
    this.password = password;
    this.groups = new ArrayList<String>();
}

public User() {

}

public String getName() {
    return this.name;
}

public String getPassword() {
    return this.password;
}

public List<String> getGroups() {
    return this.groups;
}

public String toString() {
    return "User: " + this.name + "\nGroups: " + this.groups;
}

1 个答案:

答案 0 :(得分:1)

问题是您收到415错误代码。这意味着您的/login端点不希望收到要发送给他的有效负载类型,请参见here

  

415(不受支持的媒体类型)

     

415错误响应表明,如Content-Type请求标头所示,API无法处理客户端提供的媒体类型。例如,如果API仅愿意处理格式为application / json的数据,则包含格式为application / xml的数据的客户端请求将收到415响应。

     

例如,客户端将图像上传为image / svg + xml,但是服务器要求图像使用其他格式。

我认为这是因为调用postForObject时并没有告诉您有效负载的媒体类型。因此,您需要将其包装到容纳主体的HttpEntity和标头中,以指定要转发的有效负载的媒体类型,而不是单独发送json String。试试看:

...
} else if (request.getMethod().equals("POST")) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
    HttpEntity<String> entity = new HttpEntity<>(body, headers);
    result = restTemplate.postForObject(newURL, entity, String.class);
}
...