简体   繁体   English

如何使用 RestTemplate 传递标头?

[英]How can I pass headers using RestTemplate?

In my method I initially used RestTemplate postForObject method to post request to an endpoint.在我的方法中,我最初使用RestTemplate postForObject方法将请求发布到端点。 Now I have to add default OAuth token and pass it as Post request.现在我必须添加默认的OAuth令牌并将其作为Post请求传递。 Is there any way I can pass both request as well as Default Header as part of POST request by using postForObject ?有什么方法可以使用postForObjectrequestDefault Header作为 POST 请求的一部分postForObject吗?

Initiall I used below postForObject最初我在postForObject下面postForObject

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

I am looking for something like below我正在寻找类似下面的东西

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

Here is my code这是我的代码

    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);
        } 
    }

Below is getHttpEntity which I want to pass with Post request下面是我想通过 Post 请求传递的getHttpEntity


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

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

Is there any way I can pass both request as well as Default Header as part of POST request by using postForObject?有什么方法可以使用 postForObject 将请求和默认标头作为 POST 请求的一部分传递吗?

Yes, there is a way to do that, I can give a basic example:是的,有一种方法可以做到这一点,我可以举一个基本的例子:

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 );
}

Let me know if this doesn't work!!如果这不起作用,请告诉我!!

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

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