2014-11-04 57 views
2

基本HTTP身份驗證在嘗試通過Android進行HTTP POST時工作嗎?使用Android HTTP POST進行基本身份驗證

我一直在處理一些使用基本認證的代碼,當完成一個HTTP GET請求時,它完美地工作。我需要在完成HTTP POST時使用相同的認證。

HttpPost request = new HttpPost(baseUrl+"events.json"); 
String credentials = email + ":" + password; 
String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); 
request.setHeader("Authorization", "Basic " + base64EncodedCredentials); 
request.setHeader(HTTP.CONTENT_TYPE,"application/json"); 

try 
{ 
    ArrayList<NameValuePair> vars = new ArrayList<NameValuePair>(2); 
    vars.add(new BasicNameValuePair("event[name]",currentEvent.name)); 
    vars.add(new BasicNameValuePair("event[location]",currentEvent.location)); 
    vars.add(new BasicNameValuePair("event[num_expected]",new Integer(currentEvent.num_expected).toString())); 
    request.setEntity(new UrlEncodedFormEntity(vars)); 
} catch (Exception e) { 
    // Log exception 
    Log.e("CreateEvent", "doInBackground — " + Errors.getStackTrace(e)); 
} 

HttpClient httpclient = new DefaultHttpClient(); 
try { 
    HttpResponse response = httpclient.execute(request); 

    if (response.getStatusLine().getStatusCode() == 200) { 

     HttpEntity entity = response.getEntity(); 
     String responseString = EntityUtils.toString(entity, "UTF-8"); 

     return 1; 
    } 
} 
catch (Exception e) { 
    // Log exception 
    Log.e("CreateEvent", "doInBackground — " + Errors.getStackTrace(e)); 
} 

響應是HTTP 500錯誤。它沒有返回任何細節,所以我不能確切地知道什麼是錯的,但唯一的區別是POST和表單數據的傳遞。

+0

我想這個問題與授權標題無關。那是你的服務器嗎?你能檢查日誌嗎? – momo 2014-11-04 03:09:46

回答

3

尋找更多的細節您的代碼看起來你正在設置Content-Typeapplication/json但隨後發送application/x-www-form-urlencoded數據(我想這就是UrlEncodedFormEntity一樣),因此,Web服務無法解析數據作爲JSON。

+1

Doh!多麼愚蠢的錯誤,感謝你發現莫莫! – Dexter 2014-11-04 03:18:56

+1

哈哈,它發生在我們所有人不斷;-)很高興我能幫助。 – momo 2014-11-04 03:21:37

相關問題