2012-04-20 106 views
3

我想對PHP腳本做一個簡單的HTTPRequest,並且試圖讓最基本的應用程序能夠正常工作。我想測試我的應用程序是否發送了我提供的數據,所以我已經將android應用程序發送到服務器,並且該服務器應該向我發送我放入應用程序的數據。 「postData」函數的代碼是將數據從android發送到服務器,「default.php」的代碼是在Web服務器上接收php文件,然後將數據轉發到我的電子郵件地址(未給出)。下面是代碼Android上的HTTP POST

public void postData() { 

    // Create a new HttpClient and Post Header 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost("http://somewhere.net/default.php"); 

    try { 
     // Add your data 
     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
     nameValuePairs.add(new BasicNameValuePair("thename", "Steve")); 
     nameValuePairs.add(new BasicNameValuePair("theage", "24")); 
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

     // Execute HTTP Post Request 
     //HttpResponse response = httpclient.execute(httppost); 

     // Execute HTTP Post Request 
     ResponseHandler<String> responseHandler=new BasicResponseHandler(); 
     String responseBody = httpclient.execute(httppost, responseHandler); 

    //Just display the response back 
    displayToastMessage(responseBody); 

    } catch (ClientProtocolException e) { 
     // TODO Auto-generated catch block 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
    } 
} 

以及爲「如default.php」

<?php 
$thename=$_GET["thename"]; 
$theage=$_GET["theage"]; 

$to = "[email protected]"; 
$subject = "Android"; 
$body = "Hi,\n\nHow are you," . $thename . "?\n\nAt " . $theage . " you are getting old."; 
if (mail($to, $subject, $body)) 
{ 
echo("<p>Message successfully sent!</p>"); 
} 
else 
{ 
echo("<p>Message delivery failed...</p>"); 
} 
?> 

下面是引擎收錄的鏈接代碼:然而 postData()default.php

我收到一封電子郵件發送「thename」和「theage」的數據似乎是空的。確切收到的電子郵件是 「嗨, 你好嗎?? 在你變老了。」 它向我表明服務器發送的名稱和用法爲空。你有沒有嘗試過嗎?我做錯了什麼? 非常感謝您花時間閱讀我的代碼,並且如果可能的話回覆我的問題。

編輯:我很愚蠢 - >「GETS」需要更改爲「POST」。將其留在此處用於歸檔目的:)

回答

10

您正在使用$_GET而不是$_POST來獲取發佈數據的值。你想

<?php 
$thename=$_POST["thename"]; 
$theage=$_POST["theage"]; 
1

您發送POST請求,但你的PHP腳本使用GET變量

嘗試

$thename=$_POST["thename"]; 
$theage=$_POST["theage"]; 
+0

感謝名單只是嘗試它和它的作品。我會盡快接受。 – user901898 2012-04-20 12:27:51

-1

的方法,Android和PHP應該同中都使用,無論是GETPOST

在這種情況下,你可以將PHP改變這一點 -

$thename = $_POST["thename"]; 
$theage = $_POST["theage"]; 

或者長安醚:Android的一面看 -

HttpGet httppost = new HttpGet("http://somewhere.net/default.php"); 
+0

這似乎試圖回答這個問題,但答案對我來說很不清楚。你可以查看自己的答案,編輯它,並將其作爲代碼澄清一點,並將樣式代碼作爲代碼(使用反引號或代碼塊;在選擇代碼時使用編輯字段上方的按鈕)? – Sumurai8 2015-01-26 10:09:19