android向阿里云服务器的数据传输功能实现教程
程序员文章站
2022-05-02 16:29:37
查阅了很多资料,修改了别人的代码,终于实现了android向阿里云服务器的数据传输功能。以下说说自己的步骤:
1、软硬件环境
android studio 3.2.2阿里云服务器 ( windows...
查阅了很多资料,修改了别人的代码,终于实现了android向阿里云服务器的数据传输功能。以下说说自己的步骤:
1、软硬件环境
android studio 3.2.2阿里云服务器 ( windows sever 2012 )软件集成包xampp(apach、 mysql)小米4
2、创建mysqlpersondb 以及 表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="https://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="https://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数据库插入数据的按钮,在里面输入数据,单击确定就可以向数据库中插入数据了,通过查询数据库,可以查看数据是否插入成功。