質問

I am trying to connect to a RESTful web service from an Android client.

However, I always get a HttpClientErrorException: 401 Unauthorized even if provide the correct authorization token in the request header.

The url provided is correct.

I have also tried with this request factory:

template.setRequestFactory(new SimpleClientHttpRequestFactory());

If i use Postman for Chorme with the same headers and url I get a response.

This is my code:

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();
}}
役に立ちましたか?

解決

Problem solved. I just had to update Maven dependencies.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top