简体   繁体   中英

Android Java Http Post to PHP server is always NULL?

I've researched all the internet and found articles on How to use http post from android to php server. I'm not looking for examples of how to pass data from android to website. I'm looking for reasons why POST variable is always NULL in PHP. Is there some setting I need to check for on PHP (I've checked the output buffering, max post, etc) or import a class for the HTTP POST to work correctly for POST variable.

The below codes basically insert values into mysql database. Because the POST variables are blank, it's inserting blank rows. This verified that it's connecting to my server/database, but the POST values are not being passed. Any idea? =)

Below are the codes:

    //Java Code-------------------------------------------------
    public static void executeHttpGet(Context context, String urlName){
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    String postURL = G.GetUrl(urlName);
    HttpPost httpPost = new HttpPost(postURL);
        httpPost.setHeader("Accept", "text/html,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

    try {
        nameValuePairs.add(new BasicNameValuePair("value1", "My Name"));
        nameValuePairs.add(new BasicNameValuePair("value2", "My Address"));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));
        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httpPost);

    } catch (ClientProtocolException e) {

    } catch (IOException e) {

    }
} 

    //PHP code ----------------------------------------------------
    connectMySQL();

    mysql_query("
       INSERT INTO myhome(myname,myaddress,createdate)
       VALUES('{$_POST['value1']}','{$_POST['value2']}',NOW())
    ;")
    or die(mysql_error());

Can you try to print $_POST['value1'] and $_POST['value2'] before using them in your SQL and see what they print?

For the sake of simplicity I would suggest you rewrite your PHP code:

connectMySQL();
$value1 = trim($_POST['value1']);
$value2 = trim($_POST['value2']);
if ($value1 != "" && $value2 != "") {
    mysql_query("
       INSERT INTO myhome(myname,myaddress,createdate)
       VALUES('".$value1."','".$value2."',NOW())
    ;")
}

Also, once you have verified it is working, I highly recommend you read about SQL injection attacks and try to use bind variables or parameterized queries instead of directly using request parameter values in your SQL statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM