我遇到了在以下场景中调用REST API的问题
str = < html>.....< /htm>
)Rest客户端代码(webappA):
RestTemplate restTemplate = new RestTemplate().getForObject(serverUrl, String.class);
服务器代码(webappB):请注意,此代码将不存在于旧版本/ war / webappB版本中
@RequestMapping(value = "/xyz.htm")
public ResponseEntity<String> apiMethod(HttpServletRequest request, HttpServletResponse response) {
return (new ResponseEntity<String>(responseBody, HttpStatus.OK));
}
如何解决此问题,而不是将响应字符串作为登录页面(例如str = "< html>.........< /htm>"
)。我需要一些来自spring的东西,其中客户端webappA可以识别。
提前致谢。
答案 0 :(得分:1)
如果没有找到webappA请求的特定网址的处理程序,请按照以下步骤从webappB获取JSON响应:
按如下方式编辑您的web.xml:
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/location/of/servlet_context.xml</param-value>
</init-param>
<init-param>
<param-name>throwExceptionIfNoHandlerFound</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
现在在Controller或GlobalExceptionHandler类中编写ExceptionHanler
@ExceptionHandler
public ResponseEntity<JSONReturned> exception(NoHandlerFoundException exception){
ResponseEntity<JSONReturned> responseEntity = null;
JSONReturned jsonReturned = new JSONReturned();
jsonReturned.setMsg("Sorry your request cannot be completed.");
jsonReturned.setResponse("Requested URL is not present.");
responseEntity = new ResponseEntity<JSONReturned>(jsonReturned, HttpStatus.BAD_REQUEST);
return responseEntity;
}
JSONReturned是一个用于传递消息的简单POJO类:
public class JSONReturned {
private String msg;
private String response;
//getters and setters
}
答案 1 :(得分:1)
您从REST API获取404,因为该路径尚未存在。您可以将服务器(webappB)中的默认404响应更改为您喜欢的内容。 https://spring.io/guides/tutorials/bookmarks/