【问题标题】:Why is the ResponseEntity always null using RestTemplate?为什么使用 RestTemplate 的 ResponseEntity 总是为空?
【发布时间】:2020-03-04 10:27:52
【问题描述】:

我想做一个postForEntity,但结果始终为空。可能是什么原因?

@Override
public ResponseEntity<Void> updateContactProperty(final Long contactId, final String json) throws RestClientException {

    ResponseEntity<Void> crmResponse = null;
    try {
        crmResponse = crmRestTemplate.postForEntity(
                "https://api.hubapi.com/contacts/v1/contact/vid/400000001/profile?hapikey=myApiKey", json, Void.class);
    }  catch (HttpClientErrorException e) {
        e.printStackTrace();
    } catch (HttpStatusCodeException e) {
        e.printStackTrace();
    }catch (RestClientException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } catch (Error r) {
        r.printStackTrace();
    } catch (Throwable t) {
        t.printStackTrace();
    }

    return crmResponse;
}

我试过ResponseEntity&lt;Void&gt;、ResponseEntity&lt;Object&gt;、ResponseEntity&lt;String&gt;。

向 RestTemplate 注册的 MessageConverters:

  1. ByteArrayHttpMessageConverter
  2. StringHttpMessageConverter
  3. ResourceHttpMessageConverter
  4. SourceHttpMessageConverter
  5. AllEncompassingFormHttpMessageConverter
  6. Jaxb2RootElementHttpMessageConverter
  7. MappingJackson2HttpMessageConverter

不能捕获任何异常...调用只是进行,但没有任何反应。

【问题讨论】:

  • 不,好像不一样。
  • Object.class 而不是 Void.class
  • 正如您在我的问题中看到的那样,我已经尝试使用 ResponseEntity、ResponseEntity、ResponseEntity。

标签: spring-boot null resttemplate


【解决方案1】:

问题在于所请求的 API 以 HttpStatusCodeException 和空正文响应。 HttpStatusCodeException 派生自 RestClientException 并且因为我首先捕获了 RestClientException,所以它已经被消耗了,而且我没有在捕获它之后将异常填充到我的 updateContactProperty(...) 方法的调用者,因此调用者从未注意到响应(或异常)返回。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-20
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多