问题描述
我正在将应用程序/json 类型从邮递员客户端发送到 Java API,该 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
文件)。
我已经通过邮递员测试了登录 API 并且它可以工作,但是当我尝试将其连接到该转发 API 时,出现以下错误:
org.springframework.web.client.HttpClientErrorException: 415 null。
我想知道我做错了什么或替代方法。
邮递员电话
第二个端点代码
传递给第二个端点的正文的值
用户类
公共类用户{
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楼
问题是您收到了415
错误代码。
这意味着您的/login
端点不期望您发送给他的有效负载类型,请参见
415(不支持的媒体类型)
415 错误响应表明 API 无法处理客户端提供的媒体类型,如 Content-Type 请求标头所示。 例如,如果 API 仅愿意处理格式为 application/json 的数据,则包含格式为 application/xml 的数据的客户端请求将收到 415 响应。
例如,客户端上传图片为image/svg+xml,但是服务器要求图片使用不同的格式。
我认为这是因为当你调用postForObject
,你没有告诉你的有效负载的媒体类型。
因此,不是单独发送 json 字符串,而是需要将其包装到一个HttpEntity
,该HttpEntity
包含主体和指定要转发的有效负载的媒体类型的标头。
试试这个:
...
} 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);
}
...