简体   繁体   English

如何使用Jersey Client将HTTP 400响应解析为Java类?

[英]How to parse HTTP 400 response using Jersey Client into a Java Class?

I am using Jersey client to interact with the Facebook Graph API. 我正在使用Jersey客户端与Facebook Graph API进行交互。 The Jersey client helps me parse JSON responses into Java classes. Jersey客户端帮助我将JSON响应解析为Java类。

Sometimes Facebook sends a 400 response along with useful information about the reason for the 400 response. Facebook有时会发送400响应以及有关400响应原因的有用信息。 For example: {"error":{"message":"Error validating application. Cannot get application info due to a system error.","type":"OAuthException","code":101}} 例如: {"error":{"message":"Error validating application. Cannot get application info due to a system error.","type":"OAuthException","code":101}}

Jersey simply throws an exception and eats up the useful part of the response :-( 泽西岛只是抛出异常并吃掉响应的有用部分:-(

How do I get it to parse the JSON into a Java class with fields corresponding to the useful error information? 我如何让它将JSON解析为Java类,其中的字段对应于有用的错误信息?

You can use ObjectMapper for that purpose. 您可以使用ObjectMapper来实现此目的。 Basically, create an object that will match up with the content in the JSON and use readValue() method of the mapper to turn the JSON response into an object. 基本上,创建一个与JSON中的内容匹配的对象,并使用mapper的readValue()方法将JSON响应转换为对象。

this code works: 这段代码有效:

try {
  User user = user_target
      .request()
      .get(User.class);
  System.out.println(user);
} catch (ClientErrorException primary_exception) {
  try {
    ErrorResponse error_response = primary_exception.getResponse().readEntity(ErrorResponse.class);
    System.out.println(error_response);
  } catch (ClientErrorException secondary_exception) {
    System.err.println("Secondary Exception: " + secondary_exception.getMessage());
    throw new ThisAppException("Secondary Exception", secondary_exception);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM