我想對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」。將其留在此處用於歸檔目的:)
感謝名單只是嘗試它和它的作品。我會盡快接受。 – user901898 2012-04-20 12:27:51