从Android应用程序发送POST数据到PHP

时间:2014-08-03 23:52:12

标签: java php android post

我花了好几个小时试图弄清楚为什么这不起作用。它在线匹配许多教程和示例。

我正在尝试将这四个变量作为POST request发送到我拥有的PHP页面。 POST数据永远不会进入mySQL数据库。

我已经单独测试了PHP代码并且它有效。我还为清单添加了互联网许可。

爪哇:

private class MyPost extends AsyncTask<Void, Void, Void> 
{
    @Override
    protected Void doInBackground(Void... arg0) 
    {
        Log.i("Webview", "Post Reequest Started");
        HttpClient httpClient = new DefaultHttpClient();
        // replace with your url
        HttpPost httpPost = new HttpPost(
                "http://www.notguiltyapp.com/commentform.php");

        // Post Data
        List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(4);
        nameValuePair.add(new BasicNameValuePair("name", "name1"));
        nameValuePair.add(new BasicNameValuePair("comment", "comment"));
        nameValuePair.add(new BasicNameValuePair("Judge", "Judge1"));
        nameValuePair.add(new BasicNameValuePair("add", "true"));

        // Encoding POST data
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
        } catch (UnsupportedEncodingException e) {
            // log exception

            e.printStackTrace();
        }

        // making POST request.
        try {
            HttpResponse response = httpClient.execute(httpPost);
            // write response to log
            Log.d("Http Post Response:", response.toString());
        } catch (ClientProtocolException e) {
            // Log exception

            e.printStackTrace();
        } catch (IOException e) {
            // Log exception

            e.printStackTrace();
        }
        return null;

    }
}

PHP:

<?php

if(isset($_POST['add'])){   
    $name = $_POST['name'];
    $Judgename = $_POST['Judge'];
    $IP= $_SERVER['REMOTE_ADDR'];
    $Datestamp = date("F j, Y");
    $comment = $_POST['comment'];   
    if($name){      
        if($comment){
            mysql_connect("serverip","username","password");
            mysql_select_db("comments");
            $safename = mysql_real_escape_string($name);
            $safecomment = mysql_real_escape_string($comment);
            mysql_query("INSERT INTO comments (id, name, comment, Judge, IP, Date) VALUES ('','$safename','$safecomment','$Judgename','$IP','$Datestamp')");
        }
        else
            echo "Empty Comment!";  
    }
    else
        echo "Empty Name!";
}

?>

0 个答案:

没有答案