2013-07-27 43 views
2

我想從我的android應用程序發送用戶的電子郵件地址和密碼到數據庫通過POST登錄。通過POST發送登錄細節來自android123

在服務器端,我得到我的數據是這樣的:

$email = $_POST['email']; 
$password = clean($_POST['password']; 

而且在Android方面我把它像這樣:

HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost("some real URL"); 
    httppost.setHeader("Content-type", "application/json"); 

    List<NameValuePair> params = new ArrayList<NameValuePair>(2); 
    params.add(new BasicNameValuePair("email", email)); 
    params.add(new BasicNameValuePair("password", password)); 

    httppost.setEntity(new UrlEncodedFormEntity(params)); 

    // Execute the request 
    HttpResponse response; 
    try { 
     response = httpclient.execute(httppost); 
     ...... 

即使當我在合法的登錄信息輸入,它失敗了,並說沒有電子郵件地址或密碼。我是否正確地發送信息?

我也試過在下面發送數據,但沒有工作。有什麼建議麼?

JSONObject obj = new JSONObject(); 
    obj.put("email", email); 
    obj.put("password", password); 

    httppost.setEntity(new StringEntity(obj.toString())); 
+0

可能重複不發送數據](http://stackoverflow.com/questions/10248297/android-http-post-not-sending-data) – cxzp

+0

在其他線程找到答案,問題的內容是相同的答案是頭是錯的 – cxzp

回答

0

HttpPost.setEntity設置請求的主體沒有任何名稱/值配對,只是原始post數據。 $ _POST不會查找原始數據,只是名稱值對,它會將其轉換爲散列表/數組。您可以格式化請求,使其包含名稱值對。

List<NameValuePair> params = new ArrayList<NameValuePair>(2); 
params.add(new BasicNameValuePair("json", json.toString())); 

httppost.setEntity(new UrlEncodedFormEntity(params)); 

而且在JSON對象中的參數爲:

JSONObject json = new JSONObject(); 
json.put("email", email); 
json.put("password", password); 

在服務器端,你可以得到的數據爲:

$jsonString = file_get_contents('php://input'); 
$jsonObj = json_decode($jsonString, true); 

if(!empty($jsonObj)) { 
    try { 
     $email = $jsonObj['email']; 
     $password = $jsonObj['password']; 
    } 
} 
[Android的HTTP POST的