- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
摘要:我从服务器应用程序向另一个端点发送请求。我收到 Http 401 错误响应。当我尝试将此错误主体映射到我的错误类时,我收到如下异常:
com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input
详细信息:我使用 Spring Boot 和 jackson-datatype-jsr310 开发一个服务器应用程序。我在向另一个服务器应用程序发送请求时使用 Spring 框架的 RestTemplate,例如:
public abstract class AbstractBackendAdapter {
@Autowired
private RestTemplate restTemplate;
@Autowired
private ObjectMapper mapper;
private <T> T exchange(final String url, final HttpMethod method, final HttpEntity request,
final Class<T> responseType) {
...
final ResponseEntity<T> response;
try {
response = restTemplate.exchange(url, method, request, responseType);
} catch (HttpServerErrorException exception) {
throw new BackendHttpServerException(exception, method, url, request.getHeaders());
} catch (HttpClientErrorException exception) {
throw new BackendHttpClientException(exception, method, url, request.getHeaders());
} catch (HttpMessageNotReadableException exception) {
throw new BackendHttpMessageNotReadableException(exception, method, url, request.getHeaders());
}
...
}
我不使用默认的 Spring 错误处理。相反,我编写了异常处理程序类,如下所示:
@RestControllerAdvice
public class RestResponseEntityExceptionHandler {
@Autowired
private ObjectMapper mapper;
@Autowired
private HttpServletRequest httpServletRequest;
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = {BackendHttpClientException.class})
@ResponseBody
protected ErrorResponse handleBackendClientException(final BackendHttpClientException exception,
final HttpServletResponse response) {
...
if (HttpStatus.BAD_REQUEST == httpStatus) {
...
} else if (HttpStatus.UNAUTHORIZED == httpStatus) {
final ClientErrorInfo error;
try {
error = mapper.readValue(exception.getResponseBodyAsString(), ClientErrorInfo.class);
final String errorCode = error.getErrorCode();
logBackendError(httpMethod, url, headers,
httpStatus, errorCode, error.getErrorMessage(), error.getErrorCause());
errorResponse = errorResponseConverter.prepareErrorResponse(errorCode, response);
} catch (IOException ioException) {
errorResponse = generateUnexpectedJsonFormatError(ioException);
}
}
return errorResponse;
}
但是,在某些情况下,我收到正文为空的 Http 401 响应。我的意思是,Exception.getResponseBodyAsString() 返回 null。因此,mapper.readValue(exception.getResponseBodyAsString(), ClientErrorInfo.class) 无法将 null 值解析为 ClientErrorInfo.class。然后,JsonMappingExcepiton 被抛出到行 - mapper.readValue(exception.getResponseBodyAsString(), ClientErrorInfo.class)。相关日志类似于:
com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input
at [Source: ; line: 1, column: 0]
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:270)
at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:3854)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3799)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2858)
at com.commencis.butterfly.core.RestResponseEntityExceptionHandler.handleBackendClientException(RestResponseEntityExceptionHandler.java:145)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
at org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver.doResolveHandlerMethodException(ExceptionHandlerExceptionResolver.java:384)
at org.springframework.web.servlet.handler.AbstractHandlerMethodExceptionResolver.doResolveException(AbstractHandlerMethodExceptionResolver.java:59)
at org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.resolveException(AbstractHandlerExceptionResolver.java:136)
at org.springframework.web.servlet.handler.HandlerExceptionResolverComposite.resolveException(HandlerExceptionResolverComposite.java:74)
at org.springframework.web.servlet.DispatcherServlet.processHandlerException(DispatcherServlet.java:1222)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1034)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:984)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:110)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.session.web.http.SessionRepositoryFilter.doFilterInternal(SessionRepositoryFilter.java:167)
at org.springframework.session.web.http.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:80)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:106)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
另一方面,当我通过 Postman 向同一端点发送相同的请求时,我收到带有填充正文的 Http 401 错误:
{
"errorCode": "ERR_C13",
"errorMessage": "Authorization failed",
"errorCause": "RETRIEVABLE_PNR_SR_CODE"
}
编辑1:通过使用 Charles,我在我的服务器应用程序和我向其发送请求的端点之间进行干预,并在我的服务器应用程序收到之前检查响应。响应类似于:
HTTP/1.1 401 Unauthorized
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=C157382C48E***9972A77DADC; Path=/crane-ticketing; Secure; HttpOnly
Set-Cookie: rememberMe=deleteMe; Path=/crane-ticketing; Max-Age=0; Expires=Tue, 04-Dec-2018 13:38:02 GMT
Content-Type: application/json;charset=UTF-8
Content-Length: 100
Date: Wed, 05 Dec 2018 13:38:01 GMT
Connection: Keep-alive
{"errorCode":"ERR_C13","errorMessage":"Authorization failed","errorCause":"RETRIEVABLE_PNR_SR_CODE"}
EDIT-2: application.properties 中的一些 spring-jackson 配置行,例如:
spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS = false
spring.jackson.serialization.FAIL_ON_EMPTY_BEANS = false
spring.jackson.deserialization.ADJUST_DATES_TO_CONTEXT_TIME_ZONE = false
spring.jackson.default-property-inclusion=NON_ABSENT
spring.jackson.mapper.AUTO_DETECT_GETTERS=false
如何在我的服务器应用程序中看到与 Postman 中的错误响应相同的带有填充正文的错误响应?任何想法将不胜感激!
最佳答案
经过一些调试,我意识到问题的原因是SimpleClientHttpResponse中的代码,它是Resttemplate的默认响应类。另外,我发现 Spring JIRA 中存在一些关于此问题的问题:
引用:https://jira.spring.io/browse/SPR-9367
“使用默认设置在 RestTemplate 中处理 401 响应非常困难(不可能)。事实上这是可能的,但您必须提供错误处理程序和请求工厂。错误处理程序很明显,但问题是默认请求工厂使用 java.net,当您尝试查看响应的状态代码时(尽管它显然可用),它可能会抛出 HttpRetryException。解决方案是使用 HttpComponentsClientHttpRequestFactory。”
当我在 POM 文件中添加下面编写的依赖项时,我的应用程序开始处理 401 响应的正文。
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
关于java - com.fasterxml.jackson.databind.JsonMappingException : No content to map due to end-of-input in Spring Boot App,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54022183/
我以为我有一个父类参数,它有2个子类 ComboParameter 和 IntegerParameter @JsonSubTypes({ @JsonSubTypes.Type(value =
运行以下行时: Request> requestMap = JsonUtils.fromJson(eventContext.getMessage().getPayloadAsString(), Req
我已经使用 jersey 在 java 中编写了一个 REST API。当我使用 XML 请求时,一切正常,但当我使用 JSON 请求时,我总是得到 JsonMappingException。 这些对
我使用spring RestTemplate并将json响应转换为pojo。但得到一个 JsonMappingException POJO @Root public class Account { @
我的此类带有一个标有 @JsonCreator 的构造函数,用于将 JSON 字符串反序列化到我的类 Meal 中: public class Meal { private int prote
我的 IDE 在 mapper.readValue 行给我错误 Unhandled Exception com.fasterxml.jackson.databind.JsonMappingExcept
我在 Java 中有一个通用类型的类。它应该在收到一些 json 后返回一个 T 类型的对象。我正在使用以下代码创建对象: ObjectMapper mapper = new ObjectMapper
我有一个用 Java (spring boot) 编写的 rest api,我的请求从请求 header 中获取一个 json 字符串(不要问为什么这样:),例如{flowerId: 123}在我的
我正在尝试向我的网页显示数据库数据。当 GET 请求到 @RequestMapping(value = "/api/binder") 时,我做了以下代码。 但是当获取请求到达此方法时,它会获取数据(我
我正在构建一个使用并返回 JSON 的 RESTful Web 服务。当我尝试通过服务层从数据库中获取 ESRBRating 对象时,我遇到了以下堆栈跟踪。但是,当我将 Spring Data JPA
我在 Camel Route 中遇到了异常 Caused by: com.fasterxml.jackson.databind.JsonMappingException: No serializer
对传递给 ObjectMapper Json 解析器方法的字符串进行 null 和空检查时,出现异常。这是我的代码: private static final ObjectMapper OBJECT_
我正在使用 Retrofit 2 和 jackson 转换器下载并解析此 json `{ "message": "Action complete.", "successCode": 0,
我知道关于我会告诉你的同一个问题有很多问题,但还没有一个能解决我的问题。 我已经实现了一项服务,该服务必须通过延迟加载来访问对象属性。这是类的简化: @Entity public class Trea
我有一个类需要使用 Jackson 从 JSON 反序列化。类结构如下所示: public class A { public B b; } public class B { publi
我尝试反序列化包含空属性并具有 JsonMappingException 的对象。 我的工作: String actual = "{\"@class\" : \"PersonResponse\","
尝试反序列化 JSON 时遇到以下异常 No suitable constructor found for type [simple type, class MyObj$obj$Card]: can
我有一个 Web 应用程序,其中服务器以 JSON 格式返回任何结果。为了创建 JSON,我使用 codehaus Jackson ObjectWriter 版本 1.9.8。 我遇到的问题是映射中有
我在尝试放置“可选实体过滤”时遇到问题。我有一个抽象类,如下所示: // In your Pom org.glassfish.jersey.ext je
尝试使用 @JsonIdentityInfo jackson 注释时出错。当我尝试反序列化对象时,出现以下异常: Could not read JSON: Already had POJO for i
我是一名优秀的程序员,十分优秀!