2012-06-29 33 views
0

上下文:在Android中,當我使用Java的HttpURLConnection對象(如下所示)時,我在服務器端正確地看到POST主體。但是,當我使用我認爲相當的HttpClient代碼時,POST正文爲空。在Android上使用httpclient時發佈主體爲空

問題

  1. 我缺少什麼?

  2. 服務器端是一個Django-python服務器。我在這個端點的入口點設置了一個調試點,但是帖子主體已經是空的了。我怎樣才能通過它進行調試,找出爲什麼身體是空的?

:我已經看了this,但解決方案並不爲我工作。

代碼:使用HttpURLConnection的 - 這工作:

try { 
    URL url = new URL("http://10.0.2.2:8000/accounts/signup/"); 
    String charset = "UTF-8"; 
    HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
    connection.setRequestMethod("POST"); 
    connection.setDoOutput(true); 
    connection.setRequestProperty ("Authorization", "Basic base64encodedstring=="); 
    connection.setRequestProperty("Accept-Charset", charset); 
    connection.setRequestProperty("Content-Type", 
     "application/x-www-form-urlencoded; charset=" + charset); 
    connection.setDoInput(true); 

    StringBuilder sb = new StringBuilder(); 
    sb.append("appver=6&user=value1pw=&hash=h1"); 

    OutputStreamWriter outputWriter = new 
     OutputStreamWriter(connection.getOutputStream()); 
    outputWriter.write(sb.toString()); 
    outputWriter.flush(); 
    outputWriter.close(); 
    // handle response 
} catch() { 
    // handle this 
} 

=============================== =============================

代碼:使用Apache httpclient - 不工作 - 服務器獲取空POST主體:

HttpPost mHttpPost = new HttpPost(""http://10.0.2.2:8000/accounts/signup/""); 
    mHttpPost.addHeader("Authorization", "Basic base64encodedstring=="); 
    mHttpPost.addHeader("Content-Type", 
     "application/x-www-form-urlencoded;charset=UTF-8"); 
    mHttpPost.addHeader("Accept-Charset", "UTF-8"); 

    String str = "appver=6&user=value1pw=&hash=h1"; // same as the above 
    StringEntity strEntity = new StringEntity(str); 
    mHttpPost.setEntity(strEntity); 

    HttpUriRequest pHttpUriRequest = mHttpPost; 

    DefaultHttpClient client = new DefaultHttpClient(); 
    httpResponse = client.execute(pHttpUriRequest); 
    // more code 

回答

1

我想通爲什麼這發生的原因:

POST請求中的授權頭有一個額外的新行字符「\ n」 - 這導致請求通過服務器端處理程序,但正文被切斷。我從未注意過這種行爲。

+0

你是否設法解決這個問題?我現在幾乎已經脫髮了。 –

+0

@Yati,是的,如上所述,出現此錯誤的原因是由於auth頭部末尾有無關字符。通過修剪標題檢查你的消除這些空間 –

相關問題