Android向服务器的数据库MySQL传输数据:经过修正的 Android(安卓)+ HTTP + xampp +mysql : Post / Get
16lz
2021-01-24
查阅了很多资料,修改了别人的代码,终于实现了android向阿里云服务器的数据传输功能。以下说说自己的步骤:
1、软硬件环境
- Android Studio 3.2.2
- 阿里云服务器 ( Windows Sever 2012 )
- 软件集成包XAMPP(Apach、 MySql)
- 小米4
2、创建MySQL数据库 persondb 以及 表 persons
3、服务器端代码
a.先写个配置文件db_config.php
<?phpdefine('DB_USER', "root"); // db userdefine('DB_PASSWORD', "root"); // db password (mention your db password here)define('DB_DATABASE', "persondb"); // database namedefine('DB_SERVER', "localhost"); // db server?>
b.连接MySQL数据库的文件db_connect.php
<?phpfunction connect() { /*包含并运行指定的文件*/ // import database connection variables require_once __DIR__ . '/db_config.php'; global $con; // Connecting to mysql database $con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysqli_connect_error()); // Selecing database $db = mysqli_select_db($con,DB_DATABASE) or die(mysqli_error($con)) ; // returing connection cursor return $con; }/** * Function to close db connection*/ function close() { // closing db connection global $con; mysqli_close($con); } ?>
c. Android客户端从MySQL数据库里获取数据的文件get_all_persons.php
<?php/* * Following code will list all the products */// array for JSON response$response = array();// include db connect classrequire_once __DIR__ . '/db_connect.php';// connecting to dbconnect();// get all products from products table$result = mysqli_query($con,"SELECT *FROM persons") or die(mysqli_error());// check for empty resultif (mysqli_num_rows($result) > 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
<?php $result = file_get_contents('php://input'); $object=json_decode($result); $Id_P = $object->{'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 fieldsif (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
<?xml version="1.0" encoding="utf-8"?>
该布局文件是Android客户端向MySQL数据库插入数据时的一个自定义对话框的布局文件dialog_custom.xml
<?xml version="1.0" encoding="utf-8"?>
最后出场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数据库插入数据的按钮,在里面输入数据,单击确定就可以向数据库中插入数据了,通过查询数据库,可以查看数据是否插入成功。
更多相关文章
- Android(安卓)studio 通过以servlet搭建的服务器访问 PC端 mysql
- Android使用addView动态添加组件
- Android输入系统(三):加载按键映射
- Android的NDK开发(5)————Android(安卓)JNI层实现文件的read
- Android保存数据的技巧
- Android(安卓)通过Socket 和服务器通讯
- Android(安卓)编译,打包、签程名详细教
- 一步一步学习androidNDK编程(hello world)
- 8大你不得不知的Android调试工具