【问题标题】:How can I pass headers using RestTemplate?如何使用 RestTemplate 传递标头?
【发布时间】:2020-01-23 03:08:39
【问题描述】:

在我的方法中,我最初使用RestTemplate postForObject 方法将请求发布到端点。现在我必须添加默认的OAuth 令牌并将其作为Post 请求传递。有什么方法可以使用postForObjectrequestDefault Header 作为POST 请求的一部分传递?

最初我在下面使用postForObject

 String result = restTemplate.postForObject(url, request, String.class);

我正在寻找类似下面的东西

             restTemplate.exchange(url,HttpMethod.POST,getEntity(),String.class );

这是我的代码

    private final String url;
        private final MarkBuild header;

    public DataImpl(@Qualifier(OAuth) MarkBuild header,RestTemplate restTemplate) {
               this.restTemplate= restTemplate;
                this.header = header;
    }

    public void postJson(Set<String> results){
        try {
             Map<String, String> requestBody = new HashMap<>();
             requestBody.put("news", "data");
              JSONObject jsonObject = new JSONObject(requestBody);

             HttpEntity<String> request = new HttpEntity<String>(jsonObject.toString(), null);

            String result = restTemplate.postForObject(url, request, String.class);
        } 
    }

下面是getHttpEntity,我想通过 Post 请求传递


    private HttpEntity getHttpEntity(Set <String>results) {
          return new HttpEntity<>( null, getHttpHeaders() );
    }

    private HttpHeaders getHttpHeaders() {
        return header.build();
    }
}

【问题讨论】:

  • (1) 对于此类标头,您通常应该使用拦截器(它会修改每个请求)。 (2) 你应该看看OAuth2RestTemplate,它已经为你设置了这个支持,包括来自各种来源的令牌解析。
  • 对不起,我没有得到你的问题,你在上面的代码中传递了标题对吗?
  • 是的,对,编辑了我的代码。我必须用 getHttpEntity 替换它

标签: java spring-boot post http-headers resttemplate


【解决方案1】:

有什么方法可以将请求和默认标头作为 使用 postForObject 的 POST 请求的一部分?

是的,有办法做到这一点,我可以举一个基本的例子:

HttpHeaders lHttpHeaders = new HttpHeaders();
lHttpHeaders.setContentType( MediaType.APPLICATION_JSON );//or whatever it's in your case
String payload="<PAYLOAD HERE>"
try
{
    String lResponseJson = mRestTemplate.postForObject( url, new HttpEntity<Object>( payload, lHttpHeaders ), String.class);
    return lResponseJson;
}
catch( Exception lExcp )
{
    logger.error( lExcp.getMessage(), lExcp );
}

如果这不起作用,请告诉我!

【讨论】:

  • 如果答案正确,请不要忘记给答案投票
猜你喜欢
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 2021-11-27
  • 2018-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-22
相关资源
最近更新 更多