• Android向服务器的数据库MySQL传输数据:经过修正的 Android + HTTP + xampp +mysql : Post / Get


    查阅了很多资料,修改了别人的代码,终于实现了android向阿里云服务器的数据传输功能。以下说说自己的步骤:

    1、软硬件环境

    • Android Studio 3.2.2
    • 阿里云服务器 ( Windows Sever 2012 )
    • 软件集成包XAMPP(Apach、 MySql) 
    • 小米4

    2、创建MySQL数据库 persondb  以及  表 persons

       

    3、服务器端代码

    a.先写个配置文件db_config.php

    b.连接MySQL数据库的文件db_connect.php

    c. Android客户端从MySQL数据库里获取数据的文件get_all_persons.php

     0) {
        // looping through all results
        // products node
        $response["persons"] = array();
    
        while ($row = mysqli_fetch_array($result)) {
            // temp user array
            $info = array();
            $info["Id_P"] = $row["Id_P"];
            $info["LastName"] = $row["LastName"];
            $info["FirstName"] = $row["FirstName"];
            $info["Address"] = $row["Address"];
            $info["City"] = $row["City"];
    
            // push single product into final response array
            array_push($response["persons"], $info);
        }
        // success
        $response["success"] = 1;
    
        // echoing JSON response
        echo json_encode($response);
    } else {
        // no products found
        $response["success"] = 0;
        $response["message"] = "No products found";
    
        // echo no users JSON
        echo json_encode($response);
    }
      close();
    ?>

    d.Android客户端向MySQL数据库插入数据的文件create_person.php

    {'Id_P'};
       $LastName=$object->{'LastName'};
       $FirstName=$object->{'FirstName'};
       $Address=$object->{'Address'};
       $City=$object->{'City'};
    
    /* 
     * Following code will create a new person row
     * All person details are read from HTTP Post Request
     */
    
    // array for JSON response
      $response = array();
    
    // check for required fields
    if (isset($Id_P) || isset($LastName) || isset($FirstName) || isset($Address) || isset($City)) {
    
    
        // include db connect class
        require_once __DIR__ . '/db_connect.php';
    
        // connecting to db
        connect();
    
        // mysql inserting a new row
        $result = mysqli_query($con,"INSERT INTO persons(Id_P,LastName,FirstName,Address,City) VALUES('$Id_P', '$LastName','$FirstName','$Address','$City')");
    
        // check if row inserted or not
        if ($result) {
            // successfully inserted into database
            $response["success"] = 1;
            $response["message"] = "Person successfully created.";
    
            // echoing JSON response
            echo json_encode($response);
        } else {
            // failed to insert row
            $response["success"] = 0;
            $response["message"] = "Oops! An error occurred.";
    
            // echoing JSON response
            echo json_encode($response);
        }
    } else {
        // required field is missing
        $response["success"] = 0;
        $response["message"] = "Required field(s) is missing";
    
        // echoing JSON response
        echo json_encode($response);
    }
    ?>

             

     注意: 创建一个文件夹android_connect,把以上的所有php文件都放在该文件夹里,并把android_connect 文件夹放在xampp安装目录里htdocs文件夹下。

    4.Android客户端通过网络访问MySQL数据库

    先上布局文件activity_main.xml

    
    
    
        

    该布局文件是Android客户端向MySQL数据库插入数据时的一个自定义对话框的布局文件dialog_custom.xml

    
    
        
            
            
    
        
        
            
            
        
        
            
            
        
        
            
            
    
        
    
        
        
        
         
    

    最后出场Android端的代码,各位小伙伴们注意了。

    package com.android.androidconnectserver;
    
    import android.content.DialogInterface;
    import android.content.DialogInterface.OnClickListener;
    import android.os.Bundle;
    import android.support.v7.app.AlertDialog;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import java.io.BufferedReader;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    
    public class MainActivity extends AppCompatActivity {
        public static final String TAG="MainActivity";
        private Button Send;
        private Button Receive;
        private TextView textView;
        private String response;
        private EditText inputId_P;
        private EditText inputLastName;
        private EditText inputFirstName;
        private EditText inputAddress;
        private EditText inputCity;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            initViews();
            Receive.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                   receive();
                   textView.setText(response);
    
                }
            });
            Send.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showDialog();
                }
            });
        }
    
        public void initViews(){
            Send =(Button) findViewById(R.id.Send);
            Receive= (Button) findViewById(R.id.Receive);
            textView=(TextView) findViewById(R.id.textView);
    
        }
    
        /*从MySQL里获取数据*/
        private void receive() {
            new Thread(
                    new Runnable() {
                        @Override
                        public void run() {
                            response=executeHttpGet();
                        }
                    }
    
            ).start();
        }
    
    
    
        private String executeHttpGet() {
    
            HttpURLConnection con=null;
            InputStream in=null;
            String      path="http://127.0.0.1/android_connect/get_all_persons.php";
            try {
                con= (HttpURLConnection) new URL(path).openConnection();
                con.setConnectTimeout(5000);
                con.setReadTimeout(5000);
                con.setDoInput(true);
                con.setRequestMethod("GET");
                if(con.getResponseCode()==200){
    
                    in=con.getInputStream();
                    return parseInfo(in);
                }
    
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            return null;
        }
    
        private String parseInfo(InputStream in) throws IOException {
            BufferedReader  br=new BufferedReader(new InputStreamReader(in));
            StringBuilder sb=new StringBuilder();
            String line=null;
            while ((line=br.readLine())!=null){
                sb.append(line+"\n");
            }
            Log.i(TAG, "parseInfo: sb:"+sb.toString());
            return sb.toString();
        }
    
        /*发送数据给MySQL数据库*/
        private void showDialog(){
            AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("添加个人信息");
            View view= View.inflate(MainActivity.this,R.layout.dialog_custom,null);
            builder.setView(view);
    
    
            builder.setPositiveButton("确定", new OnClickListener(){
    
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String Id_P=inputId_P.getText().toString();
                    String LastName=inputLastName.getText().toString();
                    String FirstName=inputFirstName.getText().toString();
                    String Address=inputAddress.getText().toString();
                    String City=inputCity.getText().toString();
                    try {
                        jsonObject.put("Id_P",Id_P);
                        jsonObject.put("LastName",LastName);
                        jsonObject.put("FirstName",FirstName);
                        jsonObject.put("Address",Address);
                        jsonObject.put("City",City);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    };
                    send();
                }
            });
            builder.setNegativeButton("取消",new OnClickListener(){
    
                @Override
                public void onClick(DialogInterface dialog, int which) {
    
                }
            });
    
            AlertDialog ad=builder.create();
            ad.show();
    
            inputId_P= (EditText)ad.findViewById(R.id.et_Id_P);
            inputLastName= (EditText)ad.findViewById(R.id.et_LastName);
            inputFirstName= (EditText)ad.findViewById(R.id.et_FirstName);
            inputAddress= (EditText)ad.findViewById(R.id.et_Address);
            inputCity= (EditText)ad.findViewById(R.id.et_City);
    
        }
        private void send() {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    executeHttpPost();
                }
            }).start();
    
        }
        JSONObject jsonObject=new JSONObject();
        private void executeHttpPost() {
           
            String path="http://127.0.0.1/android_connect/create_person.php";
            try {
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                //conn.setConnectTimeout(3000);     //设置连接超时时间
                conn.setDoOutput(true);  //打开输出流,以便向服务器提交数据
                conn.setDoInput(true);  //打开输入流,以便从服务器获取数据
                conn.setUseCaches(false);//使用Post方式不能使用缓存
                conn.setRequestMethod("POST");  //设置以Post方式提交数据
                //conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("Charset", "UTF-8");
                // 设置文件类型:
                //conn.setRequestProperty("Content-Type","application/json; charset=UTF-8");
                // 设置接收类型否则返回415错误
                //conn.setRequestProperty("accept","*/*")此处为暴力方法设置接受所有类型,以此来防范返回415;
                conn.setRequestProperty("accept","application/json");
              
                 // 往服务器里面发送数据
                String Json=jsonObject.toString();
    
                System.out.println("-----------    "+Json);
    
                if (Json != null && !TextUtils.isEmpty(Json)) {
                    byte[] writebytes = Json.getBytes();
                    // 设置文件长度
                    conn.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
                    OutputStream outwritestream = conn.getOutputStream();
                    outwritestream.write(Json.getBytes());
                    outwritestream.flush();
                    outwritestream.close();
                    Log.d("upload: ", "doJsonPost: "+conn.getResponseCode());//如输出200,则对了
                }
    
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    5.运行结果 
    a.向MySQL数据库插入数据 
    点击向MySQL数据库插入数据的按钮,在里面输入数据,单击确定就可以向数据库中插入数据了,通过查询数据库,可以查看数据是否插入成功。

  • 相关阅读:
    Node学习四 —— 函数执行规划
    2022亚太杯建模B题思路 : 高速列车的优化设计 小美赛数学建模 B题思路
    Windows Server 安装docker
    海关外贸企业大数据风控平台产品应用
    大规模Session-based 数据转化为邻接矩阵
    单例模式五种写法
    分享从零开始学习网络设备配置--任务3.8 使用动态路由OSPF实现网络连通
    springBoot自动装配
    Hive从入门到大牛【Hive 学习笔记】
    Go语言的Mutex
  • 原文地址:https://blog.csdn.net/weixin_67271870/article/details/126841064