[英]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
?有什么方法可以使用
postForObject
将request
和Default 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.