Trong bài viết này mình sẽ hướng dẫn các bạn tạo Web Service bằng PHP và MYSQL đơn giản, cơ bản cho những bạn mới bắt đầu tìm hiểu về web service và PHP, cụ thể là web service trong android và hướng dẫn parse json bằng thư viện retrofit với web service đã tạo. Bạn đã từng nghe về web service chưa, web service là gì và cách hoạt động của nó như thế? Nội dung chính Web services là gì ?Đặc điểm của web service Json parsing with Retrofit Đặc điểm của web service
B5: Tạo Object class đặt tên Student và để trong package modelsObject class đặt tên Student và để trong package models B6: Tạo class RetrofitClient : Tạo một database là students_manager và bảng là students bao gồm các trường : id, name, age, nclass. B7: Tạo API Interfaceuser là root, pass để trống, chọn tab SQL và pase vào đoạn code sau. #Create database CREATE DATABASE students_manager; #Create Table students CREATE TABLE students_manager.students( `id` INT(10) NOT NULL AUTO_INCREMENT, `name` VARCHAR(50) NOT NULL, `age` INT(5) NOT NULL, `nclass` VARCHAR(10) NOT NULL, PRIMARY KEY(`id`) ) ENGINE = InnoDB DEFAULT CHARSET = utf8 AUTO_INCREMENT = 1; #Insert data INSERT INTO students_manager.students(`id`, `name`, `age`, `nclass`) VALUES (1, 'Nguyễn Văn A', '20', 'KT10'), (2, 'Nguyễn Văn B', '21', 'DT5'), (3, 'Nguyễn Văn C', '20', 'KT10'), (4, 'Nguyễn Văn D', '21', 'DT5'), (5, 'Nguyễn Văn E', '21', 'CK2') B8: Tạo class ApiUtils: Tạo file php đặt tên là api.php để file này trong thư mục www của WampServer C:wamp64wwwstudent_managerapi.php
<?php DEFINE('DB_USER', 'root'); DEFINE('DB_PASSWORD', ''); DEFINE('DB_HOST', '127.0.0.1'); DEFINE('DB_NAME', 'students_manager'); $mysqli = @mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) OR die('Could not connect to MySQL'); @mysql_select_db(DB_NAME) OR die('Could not select the database'); mysql_query("SET NAMES 'utf8'"); $query = "SELECT * FROM students"; $resouter = mysql_query($query); $temparray = array(); $total_records = mysql_num_rows($resouter); if ($total_records >= 1) { while ($row = mysql_fetch_assoc($resouter)) { $temparray[] = $row; } } echo json_encode($temparray); ?> B9: Set sự kiện OnClick cho 2 Button Tạo Web Service bằng PHP và MYSQL cho ứng dụng di động – Part 1class, nhưng trong sql thì không có, lý do là mình vừa sửa lại database 1 chút thành nclass :D. Web service là một tập các phương thức được gọi thực hiện từ xa thông qua một địa chỉ http url. Kết quả trả về của web service thường dưới dạng json hoặc xml. Web service thường được sử dụng để tạo các ứng dụng phân tán.Web service cho phép bạn giao tiếp qua mạng, không phải P2P. Nó cung cấp API cho phép bạn sử dụng nó để tương tác với service hoặc bạn có thể tự tạo web service bằng PHP và MYSQL như trong bài viết này.Ví dụ bạn dùng một ứng dụng di động, ứng dụng desktop, web. Thì các ứng dụng đó gửi thông tin lên webservice rồi webservice xử lý dữ liệu bạn gửi từ app đến sever và sever xử lý xong nó sẽ trả về các dữ liệu cho bạn bằng json hay xml, để xử lý dữ liệu ở app bạn sẽ phải parse json hay parse xml.Ví dụ bạn dùng một ứng dụng di động, ứng dụng desktop, web. Thì các ứng dụng đó gửi thông tin lên webservice rồi webservice xử lý dữ liệu bạn gửi từ app đến sever và sever xử lý xong nó sẽ trả về các dữ liệu cho bạn bằng json hay xml, để xử lý dữ liệu ở app bạn sẽ phải parse json hay parse xml.
Có thể được được truy cập từ bất kỳ ứng dụng nào <?php DEFINE('DB_USER', 'root'); DEFINE('DB_PASSWORD', ''); DEFINE('DB_HOST', '127.0.0.1'); DEFINE('DB_NAME', 'students_manager'); $mysqli = @mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) OR die('Could not connect to MySQL'); @mysql_select_db(DB_NAME) OR die('Could not select the database'); mysql_query("SET NAMES 'utf8'"); if (isset($_GET["id"])) { if ($_GET["id"] == "" ) { echo ("Vui lòng nhập id"); goto end; } else { $query = "SELECT * FROM students WHERE id='" . $_GET["id"] . "'"; $resouter = mysql_query($query); } } else { $query = "SELECT * FROM students"; $resouter = mysql_query($query); } $temparray = array(); $total_records = mysql_num_rows($resouter); if ($total_records >= 1) { while ($row = mysql_fetch_assoc($resouter)) { $temparray[] = $row; } } echo json_encode($temparray); end: ?> Để xem kết quả bạn chỉ cần thêm ?id= vào sau link lúc nãy http://localhost/student_manager/api.php?id=1 . Nếu bạn để id trống http://localhost/student_manager/api.php?id= nó sẽ trả về Vui lòng nhập id.?id= vào sau link lúc nãy http://localhost/student_manager/api.php?id=1 . Nếu bạn để id trống http://localhost/student_manager/api.php?id= nó sẽ trả về Vui lòng nhập id.?id= vào sau link lúc nãy http://localhost/student_manager/api.php?id=1 . Nếu bạn để id trống http://localhost/student_manager/api.php?id= nó sẽ trả về Vui lòng nhập id. Sau khi đã có Json bạn có thể parse json bằng retrofit trong android mình đã nói ở bài trước. Json parsing with RetrofitJson parsing with RetrofitB1: Mở Android studio và tạo một project mới đặt tên WebService: Mở Android studio và tạo một project mới đặt tên WebServiceB2: Thêm thư viện retrofit vào dependencies (Module: app): Thêm thư viện retrofit vào dependencies (Module: app)dependencies { ... // Retrofit compile 'com.squareup.retrofit2:retrofit:2.2.0' // JSON Parsing compile 'com.google.code.gson:gson:2.8.0' compile 'com.squareup.retrofit2:converter-gson:2.2.0' ... } B3: Thêm quyền truy cập INTERNET vào AndroidManifest.xml<uses-permission android:name="android.permission.INTERNET" /> B4: Tạo layout cho activity_main.xml<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.dev4u.ntc.webservice.MainActivity"> <Button android:id="@+id/btnGetStudent" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Get student by ID" /> <Button android:id="@+id/btnGetStudents" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Get all students" /> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:fillViewport="true"> <TextView android:id="@+id/tvResult" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:text="Hello World!" /> </ScrollView> </LinearLayout> B5: Tạo Object class đặt tên Student và để trong package modelsObject class đặt tên Student và để trong package modelsCác thuộc tính của class Student giống y chang như các trường của database, cái hạn chế của parse json bằng Retrofit nó nằm ở đấy, tổ chức cấu trúc của Json như thế nào thì trong đối tượng trong Android phải y như thế đấy. Mình mới nghiên cứu cái thư viện này thấy như thế, không biết là có pro nào làm việc nhiều với thư viện này có cách xử lý khác không rất mong được chỉ giáo, xin cảm ơn rất nhiều. Cũng vì lý do này nên mình mới sửa class –> nclass, do lúc đầu mình tạo database là class nên đối tượng trong android cũng phải đặt theo class. Mà đặt tên thuộc tính của đối tượng là class trong android là không được phép, sẽ thông báo lỗi ngay, mà chỉ sửa class –> nclass trong android thì sẽ không parse được trường class trên webservice. Nên chỉ sửa 1 chút trên database với trong android là ok.class –> nclass, do lúc đầu mình tạo database là class nên đối tượng trong android cũng phải đặt theo class. Mà đặt tên thuộc tính của đối tượng là class trong android là không được phép, sẽ thông báo lỗi ngay, mà chỉ sửa class –> nclass trong android thì sẽ không parse được trường class trên webservice. Nên chỉ sửa 1 chút trên database với trong android là ok.class –> nclass, do lúc đầu mình tạo database là class nên đối tượng trong android cũng phải đặt theo class. Mà đặt tên thuộc tính của đối tượng là class trong android là không được phép, sẽ thông báo lỗi ngay, mà chỉ sửa class –> nclass trong android thì sẽ không parse được trường class trên webservice. Nên chỉ sửa 1 chút trên database với trong android là ok. package com.dev4u.ntc.webservice.models; /** * IDE: Android Studio * Created by Nguyen Trong Cong - NTCDE.COM * Name packge: com.dev4u.ntc.webservice.models * Name project: WebService * Date: 3/24/2017 * Time: 17:47 */ public class Student { private int id; private String name; private int age; private String nclass; public Student(int id, String name, int age, String nclass) { this.id = id; this.name = name; this.age = age; this.nclass = nclass; } @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + ''' + ", age=" + age + ", nclass='" + + ''' + '}'; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getNclass() { return nclass; } public void setNclass(String nclass) { this.nclass = nclass; } } B6: Tạo class RetrofitClientĐể sử dụng các yêu cầu mạng đến một RESTful API bằng Retrofit, chúng ta cần tạo ra một đối tượng bằng cách sử dụng lớp Retrofit Builder và cấu hình nó với một URL cơ sở. package com.dev4u.ntc.webservice.webservice; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; /** * IDE: Android Studio * Created by Nguyen Trong Cong - NTCDE.COM * Name packge: com.dev4u.ntc.webservice * Name project: WebService * Date: 3/24/2017 * Time: 17:52 */ public class RetrofitClient { private static Retrofit retrofit = null; public static Retrofit getClient(String baseUrl) { if (retrofit == null) { retrofit = new Retrofit.Builder() .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create()) .build(); } return retrofit; } } B7: Tạo API InterfaceTạo API Interface đặt tên là APIService. Interface này dùng để chứa các phương thức mà chúng ta sẽ sử dụng để gọi các yêu cầu truy vấn HTTP chẳng hạn như GET, POST, PUT, và DELETE. Ở APIService Interface này, chỗ getStudent(@Query(“id”) String id) sẽ dùng phương thức @Query của thư viện Retrofit để truy vấn dữ liệu ở ?id=.. theo như link trên browser là http://localhost/student_manager/api.php?id=.., ví dụ bạn muốn lấy student theo id và lớp chẳng hạn, bạn sẽ viết thành getStudent(@Query(“id”) String id, @Query(“nclass”) String nclass) , link trên browser sẽ là http://localhost/student_manager/api.php?id=…?nclass=…getStudent(@Query(“id”) String id) sẽ dùng phương thức @Query của thư viện Retrofit để truy vấn dữ liệu ở ?id=.. theo như link trên browser là http://localhost/student_manager/api.php?id=.., ví dụ bạn muốn lấy student theo id và lớp chẳng hạn, bạn sẽ viết thành getStudent(@Query(“id”) String id, @Query(“nclass”) String nclass) , link trên browser sẽ là http://localhost/student_manager/api.php?id=…?nclass=…getStudent(@Query(“id”) String id) sẽ dùng phương thức @Query của thư viện Retrofit để truy vấn dữ liệu ở ?id=.. theo như link trên browser là http://localhost/student_manager/api.php?id=.., ví dụ bạn muốn lấy student theo id và lớp chẳng hạn, bạn sẽ viết thành getStudent(@Query(“id”) String id, @Query(“nclass”) String nclass) , link trên browser sẽ là http://localhost/student_manager/api.php?id=…?nclass=… Ở đây còn một vấn đề nữa, Call getStudent(@Query(“id”) String id); chỉ lấy một Student theo id mà tại sao lại cần dùng List. Lý do là lúc mình code service trả về Json là một Json Array mà 1 array thì sẽ có nhiều object nên Retrofit nó sẽ hiểu và trong android bắt buộc phải để Call mặc dù trong Json Array đó chỉ có 1 Object. Nếu bạn muốn chỉ gọi Call thì lúc Service trả về Json phải là 1 Json Object.Call> getStudent(@Query(“id”) String id); chỉ lấy một Student theo id mà tại sao lại cần dùng List. Lý do là lúc mình code service trả về Json là một Json Array mà 1 array thì sẽ có nhiều object nên Retrofit nó sẽ hiểu và trong android bắt buộc phải để Call> mặc dù trong Json Array đó chỉ có 1 Object. Nếu bạn muốn chỉ gọi Call thì lúc Service trả về Json phải là 1 Json Object.Call> getStudent(@Query(“id”) String id); chỉ lấy một Student theo id mà tại sao lại cần dùng List. Lý do là lúc mình code service trả về Json là một Json Array mà 1 array thì sẽ có nhiều object nên Retrofit nó sẽ hiểu và trong android bắt buộc phải để Call> mặc dù trong Json Array đó chỉ có 1 Object. Nếu bạn muốn chỉ gọi Call thì lúc Service trả về Json phải là 1 Json Object. package com.dev4u.ntc.webservice.webservice; import com.dev4u.ntc.webservice.models.Student; import java.util.List; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; /** * IDE: Android Studio * Created by Nguyen Trong Cong - NTCDE.COM * Name packge: com.dev4u.ntc.webservice.models * Name project: WebService * Date: 3/24/2017 * Time: 17:52 */ public interface APIService { // GET students from server // Server return json array @GET("/student_manager/api.php") Call<List<Student>> getStudents(); // GET student by id student from server // Server return json object @GET("/student_manager/api.php") Call<List<Student>> getStudent(@Query("id") String id); } B8: Tạo class ApiUtilsClass ApiUtils dùng để khởi tạo Retrofit trong MainActivity và gọi các phương thức trong Interface APIService. Ở đây mình chạy trên Emulator nên url mình để là http://10.0.2.2 còn nếu bạn chạy trên Genymotion sẽ đổi thành http://10.0.2.3http://10.0.2.2 còn nếu bạn chạy trên Genymotion sẽ đổi thành http://10.0.2.3http://10.0.2.2 còn nếu bạn chạy trên Genymotion sẽ đổi thành http://10.0.2.3 package com.dev4u.ntc.webservice.webservice; /** * IDE: Android Studio * Created by Nguyen Trong Cong - NTCDE.COM * Name packge: com.dev4u.ntc.webservice * Name project: WebService * Date: 3/24/2017 * Time: 17:54 */ public class ApiUtils { public static final String BASE_URL = "http://10.0.2.2"; private ApiUtils() { } public static APIService getAPIService() { return RetrofitClient.getClient(BASE_URL).create(APIService.class); } } B8: Khởi tạo layout và Retrofit trong MainActivity<?php DEFINE('DB_USER', 'root'); DEFINE('DB_PASSWORD', ''); DEFINE('DB_HOST', '127.0.0.1'); DEFINE('DB_NAME', 'students_manager'); $mysqli = @mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) OR die('Could not connect to MySQL'); @mysql_select_db(DB_NAME) OR die('Could not select the database'); mysql_query("SET NAMES 'utf8'"); $query = "SELECT * FROM students"; $resouter = mysql_query($query); $temparray = array(); $total_records = mysql_num_rows($resouter); if ($total_records >= 1) { while ($row = mysql_fetch_assoc($resouter)) { $temparray[] = $row; } } echo json_encode($temparray); ?>0 B9: Set sự kiện OnClick cho 2 Button<?php DEFINE('DB_USER', 'root'); DEFINE('DB_PASSWORD', ''); DEFINE('DB_HOST', '127.0.0.1'); DEFINE('DB_NAME', 'students_manager'); $mysqli = @mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) OR die('Could not connect to MySQL'); @mysql_select_db(DB_NAME) OR die('Could not select the database'); mysql_query("SET NAMES 'utf8'"); $query = "SELECT * FROM students"; $resouter = mysql_query($query); $temparray = array(); $total_records = mysql_num_rows($resouter); if ($total_records >= 1) { while ($row = mysql_fetch_assoc($resouter)) { $temparray[] = $row; } } echo json_encode($temparray); ?>1 Code file MainActivity <?php DEFINE('DB_USER', 'root'); DEFINE('DB_PASSWORD', ''); DEFINE('DB_HOST', '127.0.0.1'); DEFINE('DB_NAME', 'students_manager'); $mysqli = @mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) OR die('Could not connect to MySQL'); @mysql_select_db(DB_NAME) OR die('Could not select the database'); mysql_query("SET NAMES 'utf8'"); $query = "SELECT * FROM students"; $resouter = mysql_query($query); $temparray = array(); $total_records = mysql_num_rows($resouter); if ($total_records >= 1) { while ($row = mysql_fetch_assoc($resouter)) { $temparray[] = $row; } } echo json_encode($temparray); ?>2 Xem hướng dẫn Tạo Web Service bằng PHP và MYSQL cho ứng dụng di động – Part 2 Project on Github: https://github.com/trongcong/WebServiceAndroidhttps://github.com/trongcong/WebServiceAndroidhttps://github.com/trongcong/WebServiceAndroid |