代码之家  ›  专栏  ›  技术社区  ›  Sonal

使用具有两种不同响应的Rest api

  •  0
  • Sonal  · 技术社区  · 8 年前

    我试图用两种不同的响应来使用api。当提供适当的输入和标题时,它会给出一个json对象。这在下面给出的代码中运行良好。

    但当其中一个输入或头丢失时,api会返回另一个json,该json在通过Postman时说明错误详细信息,但客户端代码无法实现这一点。它抛出异常,但api应该返回json和错误详细信息。

    首先我尝试了postForobject(),然后改为exchange(),假设postForobject返回的对象和api没有得到预期的对象格式。所以用绳子试过了。clas而不是特定的类

    如何通过点击相同的url来获得两个不同的json对象?

    成功时:

    {
        "contacts": [
            {
                "input": "98########",
                "status": "valid"
            }
        ]
    
    }
    

    输入或标题缺失时:

    "errors": [
            {
                "code": 1###,
                "title": "Access denied",
                "details": "invalid deatils"
            }
        ]
    

    下面是我的代码:

     public static void main(String[] args) throws Exception {
    
            RestTemplate restTemplate = new RestTemplate();
            String check_Contact_Async = "https://port/contacts/";
    
            sslByPass();
            //headers = setHeaders();
            contactsDTO = getInput(); 
    
            final HttpEntity<ContactsDTO> entity = new HttpEntity<ContactsDTO>(contactsDTO, headers);
    
            try {
                //WsResponse res = restTemplate.postForObject(check_Contact_Async, entity, WsResponse.class);
    
                ResponseEntity<String> responseEntity = restTemplate.exchange(
                        check_Contact_Async, HttpMethod.POST, entity,
                           String.class);
    
                System.out.println(responseEntity);
            } catch (Exception exception) {
    
                System.out.println(exception);
            } 
        }
    
    
    
    Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 401 Unauthorized
        at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)
        at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:667)
        at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:620)
        at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:580)
        at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:498)
        at com.websystique.springmvc.apitest.Example.main(Example.java:120)
    

    任何线索都会有帮助

    谢谢

    0 回复  |  直到 8 年前