0

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

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

提供的网址是正确的。

我也试过这个请求工厂:

template.setRequestFactory(new SimpleClientHttpRequestFactory());

如果我使用具有相同标题和 url 的 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();
}}
4

1 回答 1

0

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

于 2014-03-03T12:21:07.370 回答