2014-02-28 129 views
0

我試圖從Android客戶端連接到RESTful Web服務。Android RestTemplate exchange()拋出HttpClientErrorException:401未授權

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

提供的URL是正確的。

我自己也嘗試了這一要求工廠:

template.setRequestFactory(new SimpleClientHttpRequestFactory()); 

如果我使用郵差爲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(); 
}} 
+0

'AuthUtil.getCurrentUserAuthorization()'做了什麼? – holmis83

+0

AuthUtil.getCurrentUserAuthorization()返回必須添加到請求標頭的授權令牌。 – razvan

+0

您確定您正確構建授權令牌嗎? – holmis83

回答

0

問題解決了。我只需更新Maven依賴關係。