【问题标题】:HTTP POST on AndroidAndroid 上的 HTTP POST
【发布时间】:2012-04-20 12:15:56
【问题描述】:

我想为 php 脚本创建一个简单的 HTTPRequest,并且我尝试制作最基本的应用程序以使功能正常工作。我想测试我的应用程序是否正在发送我提供给它的数据,因此我已将 android 应用程序发送到服务器,并且该服务器应该向我发送我已放入应用程序的数据。 “postData”函数的代码是将数据从android发送到服务器,“default.php”的代码是网络服务器上接收的php文件,然后将数据转发到我的电子邮件地址(未给出)。这是代码

    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 = "someemail@gmail.com";
$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>");
}
?>

以下是 pastebin 中代码的链接: postData()default.php

我收到一封电子邮件,但是发送的“thename”和“theage”数据似乎是空的。收到的确切电子邮件是 “你好, 你好吗,? 在你变老了。” 这向我表明服务器正在将名称和年龄发送为空。你们有没有人试过这个?我做错了什么? 非常感谢您抽出时间阅读我的代码,并在可能的情况下回复我的问题。

编辑:我很白痴->“GETS”需要更改为“POST”。将其留在这里用于存档目的:)

【问题讨论】:

    标签: php android http-post


    【解决方案1】:

    您使用$_GET 而不是$_POST 来获取发布数据的值。你想要的

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

    【讨论】:

      【解决方案2】:

      您正在发送 POST 请求,但您的 php 脚本使用 GET 变量

      试试

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

      【讨论】:

      • Thanx 刚刚试了一下,效果很好。我会尽快接受正确的。
      【解决方案3】:

      Android 和 PHP 中使用的方法应该相同,GETPOST

      在这种情况下,您可以将 PHP 更改为此 -

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

      或者改变 Android 方面 -

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

      【讨论】:

      • 这似乎试图回答这个问题,但答案对我来说很不清楚。您可以查看自己的答案,对其进行编辑,并对其进行澄清并将代码样式设置为代码(使用反引号或代码块;在选择代码时使用编辑字段上方的按钮)?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-14
      相关资源
      最近更新 更多