2012-04-20 63 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