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

时间:2015-12-24 00:50:47

标签: java android json http-post send

我正在尝试将数据发送到WampServer。我正在使用HttpUrlConnection,我不知道如何发送数据 - 可能是JSON格式或XML。我已经使用内容值来保存我想要发送的变量的值,但我不知道如何在PHP脚本中将它们发送到POST方法。

这是PHP代码:

<?php 

if(isset($_POST['txtname'])&&isset($_POST['txtemail']))
{
    require ('config.php');
    $con=mysqli_connect($servername,$username,$password,$db);
    $txtname=$_POST['txtname'];
    $txtemail=$_POST['txtemail'];
    mysqli_query($con,"insert into users (name,email) values('$txtname','$txtemail') ");
    echo "Inserted";
}

?>

这是Java代码:

package com.subhi.addtoserver;

import android.app.ProgressDialog;
import android.content.ContentValues;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

   public EditText name,email;
    Button add;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        name=(EditText)findViewById(R.id.name);
        email=(EditText)findViewById(R.id.email);
        add=(Button)findViewById(R.id.add);
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                InsertData task1 = new InsertData();
                String name1, email1;
                name1 = name.getText().toString();
                email1 = email.getText().toString();
                task1.execute("http://192.168.1.100/add/index.php", name1, email1);

            }
        });
    }


    private class InsertData extends AsyncTask<String,Void,Boolean>
    {
        ProgressDialog dialog=new ProgressDialog(MainActivity.this);

        @Override
        protected Boolean doInBackground(String... urls) {

            for (String url: urls)
            {

                try {                      

                    ContentValues contentValues=new ContentValues();
                    contentValues.put("txtname",urls[1]);
                    contentValues.put("txtemail",urls[2]);

                    URL url1 =new URL(urls[0]);
                    HttpURLConnection urlConnection=(HttpURLConnection)url1.openConnection();
                    urlConnection.connect();

                } catch (MalformedURLException e) {
                    Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();;
                    e.printStackTrace();
                    return  false;
                } catch (IOException e) {
                    Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();;
                    e.printStackTrace();
                    return false;
                }

            }

            return true;
        }

        @Override
        protected void onPreExecute() {

            dialog.setMessage("Sending Data....");
            dialog.show();
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if(result==true)
            {

                Toast.makeText(getApplicationContext(),"Insert Success",Toast.LENGTH_LONG).show();;
            }
            else {
                Toast.makeText(getApplicationContext(),"Insert Fail",Toast.LENGTH_LONG).show();;
            }
            dialog.dismiss();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

2 个答案:

答案 0 :(得分:0)

这是你应该发送的方式。

echo json_encode(array("txtname"=>$txtname, "txtemail"=>'$txtemail'));

客户端在android中。 我希望你知道,如何从json获取值。

答案 1 :(得分:-1)

这个youtube URL用于将数据android传递给带有SQL服务器的PHP。 网址:https://www.youtube.com/watch?v=D86beKXvjd0

试试这个