Android RestTemplate exchange()抛出HttpClientErrorException:401 Unauthorized

时间:2014-02-28 10:28:35

标签: android spring unauthorized spring-android

我正在尝试从Android客户端连接到RESTful Web服务。

但是,我总是得到HttpClientErrorException: 401 Unauthorized even if provide the correct authorization token in the request header.

提供的网址是正确的。

我也尝试过这个请求工厂:

template.setRequestFactory(new SimpleClientHttpRequestFactory());

如果我使用Postman for Chorme使用相同的标题和网址,我会收到回复。

这是我的代码:

public class PutSomeObjectTask extends AsyncTask<SomeObject, Void, SomeObject>{

@Override
protected SomeObject doInBackground(SomeObject... params) {
    SomeObject object = params[0];
    String url = ...;

    RestTemplate template = new RestTemplate();
    template.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
    template.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
    template.getMessageConverters().add(new FormHttpMessageConverter());

    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/json");
    headers.set("Authorization", AuthUtil.getCurrentUserAuthorization());

    HttpEntity<SomeObject> requestEntity = new HttpEntity<SomeObject>(object, headers);
    ResponseEntity<SomeObject> responseEntity = template.exchange(url, HttpMethod.PUT, requestEntity, SomeObject.class);

    return responseEntity.getBody();
}}

1 个答案:

答案 0 :(得分:0)

问题解决了。我只需要更新Maven依赖项。