使身份验证POST请求同春RestTemplate为Android [英] Making authenticated POST requests with Spring RestTemplate for Android

查看:158
本文介绍了使身份验证POST请求同春RestTemplate为Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个RESTful API,我试图通过Android和RestTemplate连接。该API的所有请求进行身份验证与HTTP认证,通过设置HttpEntity的头,然后用RestTemplate的交换()方法。

I have a RESTful API I'm trying to connect with via Android and RestTemplate. All requests to the API are authenticated with HTTP Authentication, through setting the headers of the HttpEntity and then using RestTemplate's exchange() method.

所有GET请求工作带来极大的这种方式,但我想不出如何完成身份验证的POST请求。 postForObject postForEntity 处理的帖子,但没有简单的方法来设置身份验证头。

All GET requests work great this way, but I cannot figure out how to accomplish authenticated POST requests. postForObject and postForEntity handle POSTs, but have no easy way to set the Authentication headers.

因此​​,对于殆尽,这个伟大的工程:

So for GETs, this works great:

HttpAuthentication httpAuthentication = new HttpBasicAuthentication("username", "password");
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAuthorization(httpAuthentication);

HttpEntity<?> httpEntity = new HttpEntity<Object>(requestHeaders);

MyModel[] models = restTemplate.exchange("/api/url", HttpMethod.GET, httpEntity, MyModel[].class);

但通过POST显然不符合工作交流(),因为它永远不会发送定制的头,我不知道怎样使用<$ C将请求主体$ C>交换()。

But POSTs apparently don't work with exchange() as it never sends the customized headers and I don't see how to set the request body using exchange().

什么是从RestTemplate使身份验证的POST请求的最简单的方法?

What is the easiest way to make authenticated POST requests from RestTemplate?

推荐答案

确定找到了答案。 交换()是最好的方式。奇怪的 HttpEntity 类没有一个 setBody()方法(它有 getBody( )),但它仍然是可能的设置请求体,通过构造

Ok found the answer. exchange() is the best way. Oddly the HttpEntity class doesn't have a setBody() method (it has getBody()), but it is still possible to set the request body, via the constructor.

// Create the request body as a MultiValueMap
MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();     

body.add("field", "value");

// Note the body object as first parameter!
HttpEntity<?> httpEntity = new HttpEntity<Object>(body, requestHeaders);

MyModel model = restTemplate.exchange("/api/url", HttpMethod.POST, httpEntity, MyModel.class);

这篇关于使身份验证POST请求同春RestTemplate为Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆