gpt4 book ai didi

java - 客户端调用服务器REST API时遇到问题

转载 作者:行者123 更新时间:2023-12-02 03:08:09 25 4
gpt4 key购买 nike

我在以下场景中调用 REST API 时遇到问题

  1. 有两个Web应用程序webappA(客户端),webappB(服务器)
  2. 客户端webappA调用webappB(服务器)的API
  3. 如果客户端 webappA 调用 API,并且服务器应用程序 webappB 没有这样的 API(如果是之前的构建/ war ,在实现 API 之前),则 spring 将其重定向到登录页面,然后客户端接收 API 的响应作为登录页面作为字符串(例如 str = < html>.....< /htm> )

其余客户端代码(webappA):

RestTemplate restTemplate = new RestTemplate().getForObject(serverUrl, String.class);

服务器代码(webappB):请注意,此代码不会存在于旧版本的 webappB 中/war/版本中

@RequestMapping(value = "/xyz.htm")
public ResponseEntity<String> apiMethod(HttpServletRequest request, HttpServletResponse response) {

return (new ResponseEntity<String>(responseBody, HttpStatus.OK));
}

我如何解决这个问题,而不是获取响应字符串作为登录页面(例如 str = "< html>.........< /htm>" )。我需要来自 spring 的一些东西,其余客户端 webappA 可以识别。

提前致谢。

最佳答案

如果没有找到 webappA 请求的特定 URL 的处理程序,请按照以下步骤从 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
}

关于java - 客户端调用服务器REST API时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41440698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com