我们的应用程序中有两个部分:
服务器 - 提供 REST 服务
客户端 - 通过 Spring restTemplate 使用它们
除了 HTTP 状态之外,我们的服务器还返回一个带有 JSON 的 HTTP 正文,详细描述了错误。因此,我在 restTemplate 中添加了自定义错误处理程序,以将一些错误编码为非错误 - 它有助于很好地解析 HTTP 正文。
但是在 HTTP/1.1 401 Unauthorized 的情况下,我通过解析 HTTP 正文得到一个异常。所有其他错误代码都处理得很好(400、402 等)。我们使用普通的服务器逻辑,在错误的情况下发送 HTTP 响应,对于不同类型的错误没有特殊规则:
writeErrorToResponse(int status, String errMsg, HttpServletResponse resp) throws IOException {
response.setStatus(status);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
String message = String.format("{\"error\":\"%s\"}", StringUtils.escapeJson(errMsg));
resp.getWriter().println(message);
}
但在客户端只有 HTTP/1.1 401 抛出异常 -"java.net.HttpRetryException: cannot retry due to server authentication, in streaming mode"
我做了一些调试,发现问题的原因是 SimpleClientHttpResponse 中的代码:
HttpURLConnection.getInputStream()
使用 Fiddler 进行跟踪有以下响应:消息在客户端解析正确:
HTTP/1.1 402 Payment Required
X-Powered-By: Servlet/3.0
Content-Type: application/json
Content-Language: en-GB
Content-Length: 55
Connection: Close
Date: Sat, 25 May 2013 10:10:44 GMT
Server: WebSphere Application Server/8.0
{"error":"I cant find that user. Please try again."}
以及导致异常的消息:
HTTP/1.1 401 Unauthorized
X-Powered-By: Servlet/3.0
Content-Type: application/json
Content-Language: en-GB
Content-Length: 55
Date: Sat, 25 May 2013 11:00:21 GMT
Server: WebSphere Application Server/8.0
{"error":"I cant find that user. Please try again."}
在这种情况下,java.net.HttpRetryException 的原因可能是什么?
另外:前段时间这种机制运行良好。但是由于我们在 app.js 中更改了很多代码。