Hướng dẫn create api in php for android - tạo api bằng php cho android

bởi Vincy. Sửa đổi lần cuối vào ngày 9 tháng 7 năm 2022.

API PHP REST được sao lưu với cơ sở dữ liệu MySQL là sơ đồ rất phổ biến của ứng dụng di động doanh nghiệp. Khi kịch bản yêu cầu dữ liệu được lưu trữ theo cách tập trung, thì kiến ​​trúc này nên được sử dụng. Thông thường, cơ sở dữ liệu cục bộ trong điện thoại di động có thể được sử dụng để lưu trữ và truy xuất thông tin.

Trong hướng dẫn này, chúng tôi đang tạo một dịch vụ RESTful PHP để đọc dữ liệu từ bảng cơ sở dữ liệu (MySQL). Ngoài ra, tôi đang cung cấp một ví dụ mã dự án Android để gọi dịch vụ RESTful này.

Trong một hướng dẫn trước đây, chúng tôi đã thấy những điều cơ bản về các dịch vụ Restful của PHP. Tôi thực sự khuyên bạn nên trải qua nó trước khi tiếp tục hướng dẫn này.

Trong ví dụ này, chúng tôi đang gọi API REST PHP từ một ứng dụng Android. Ở phía máy chủ, dịch vụ API đọc dữ liệu từ cơ sở dữ liệu & NBSP; và gửi phản hồi ở định dạng JSON. Sau khi nhận được phản hồi, ứng dụng Android sẽ hiển thị hàng các mục trong ListView bằng cách phân tích dữ liệu JSON.

Nếu bạn muốn xem cách xử lý dữ liệu JSON với PHP với các ghi chú và ví dụ chi tiết, thì bài viết được liên kết sẽ là một hướng dẫn hoàn hảo về điều này.

Hướng dẫn create api in php for android - tạo api bằng php cho android

API REST PHP đọc hồ sơ MySQL

Chúng tôi có một bảng cơ sở dữ liệu chứa danh sách các tên mô hình điện thoại di động. API REST của chúng tôi lấy danh sách các tên di động từ cơ sở dữ liệu và gửi phản hồi trong JSON. API còn lại này chứa ba phần. Đó là, bộ điều khiển REST, lớp dịch vụ và DAO.

RestController.php

Các cuộc gọi còn lại hạ cánh trên bộ điều khiển này. Nó gọi dịch vụ để chuẩn bị phản hồi.

getAllMobiles();
		break;

	case "" :
		//404 - not found;
		break;
}
?>

MobileRestHanler.php

Lớp dịch vụ gọi hàm DAO để đọc dữ liệu từ bảng cơ sở dữ liệu. Vì ứng dụng của chúng tôi yêu cầu dữ liệu loại JSON, lớp dịch vụ chuẩn bị phản hồi ở định dạng JSON.

getAllMobile();

		if(empty($rawData)) {
			$statusCode = 404;
			$rawData = array('error' => 'No mobiles found!');		
		} else {
			$statusCode = 200;
		}

		$requestContentType = 'application/json';//$_POST['HTTP_ACCEPT'];
		$this ->setHttpHeaders($requestContentType, $statusCode);
		
		$result["output"] = $rawData;
				
		if(strpos($requestContentType,'application/json') !== false){
			$response = $this->encodeJson($result);
			echo $response;
		}
	}
	
	public function encodeJson($responseData) {
		$jsonResponse = json_encode($responseData);
		return $jsonResponse;		
	}
}
?>

Mobile.php

mobiles = $dbcontroller->executeSelectQuery($query);
		return $this->mobiles;
	}	
}
?>

Ứng dụng Android - Truy cập API REST PHP

Trong ví dụ này, chúng tôi đang tạo một ứng dụng Android đơn giản để truy cập dữ liệu MySQL bằng API REST trong PHP. Chúng tôi đang có một yếu tố ListView trong MainActivity.

Chúng tôi đang tạo một bộ điều hợp ListView để thêm danh sách các mục được trả về dưới dạng phản hồi API. Sau đó, chúng tôi đặt bộ điều hợp này thành phần tử ListView để hiển thị các hàng dữ liệu MySQL.

Khi khởi chạy MainActivity, chúng tôi gọi & nbsp; Asynctask để truy cập API REST MySQL REST. Chúng tôi sử dụng lớp HTTPConnectionRequest, để đặt các tham số và gửi & nbsp; yêu cầu đến API. Mã sau đây cho thấy lớp chính.

package com.phppot.code.phprestapp;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.Date;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {
    private String apiPath = "http://10.0.2.2/phpsamples/php-mysql-rest-api-for-android/mobile/list/";
    private ProgressDialog processDialog;
    private JSONArray restulJsonArray;
    private int success = 0;

    private ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = (ListView) findViewById(R.id.mobile_name_list);
        new ServiceStubAsyncTask(this, this).execute();
    }

    private class ServiceStubAsyncTask extends AsyncTask {

        private Context mContext;
        private Activity mActivity;
        String response = "";
        HashMap postDataParams;

        public ServiceStubAsyncTask(Context context, Activity activity) {
            mContext = context;
            mActivity = activity;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            processDialog = new ProgressDialog(mContext);
            processDialog.setMessage("Please  Wait ...");
            processDialog.setCancelable(false);
            processDialog.show();
        }

        @Override
        protected Void doInBackground(Void... arg0) {

            postDataParams = new HashMap();
            postDataParams.put("HTTP_ACCEPT", "application/json");

            HttpConnectionService service = new HttpConnectionService();
            response = service.sendRequest(apiPath, postDataParams);
            try {
                success = 1;
                JSONObject resultJsonObject = new JSONObject(response);
                restulJsonArray = resultJsonObject.getJSONArray("output");
            } catch (JSONException e) {
                success = 0;
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            if (processDialog.isShowing()) {
                processDialog.dismiss();
            }

            if (success == 1) {
                if (null != restulJsonArray) {
                    ArrayAdapter listViewAdapter = new ArrayAdapter(mContext, R.layout.mobile_name_listview);

                    for (int i = 0; i < restulJsonArray.length(); i++) {
                        try {
                            JSONObject jsonObject = restulJsonArray.getJSONObject(i);
                            listViewAdapter.add(jsonObject.get("name"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    listView.setAdapter(listViewAdapter);
                }
            }
        }

    }//end of async task
}

và các tệp nội dung XML là,

activity_main.xml




    

mobile_name_listview.xml



Output:

Hướng dẫn create api in php for android - tạo api bằng php cho android

Tải xuống

Trở lại đầu

Tôi có thể xây dựng API với PHP không?

Có nhiều khung tuyệt vời có thể giúp bạn xây dựng API REST một cách nhanh chóng.Nền tảng API của Laravel/lum và Symfony là những ví dụ được sử dụng thường xuyên nhất trong hệ sinh thái PHP.Chúng cung cấp các công cụ tuyệt vời để xử lý các yêu cầu và tạo các phản hồi JSON với mã trạng thái HTTP chính xác.. Laravel/Lumen and Symfony's API platform are the most often used examples in the PHP ecosystem. They provide great tools to process requests and generate JSON responses with the correct HTTP status codes.

PHP có API REST không?

Có nhiều cách bạn có thể nhận được thông tin từ API RESTful bằng PHP..

API PHP RESTful là gì?

API REST là API cho phép các lập trình viên gửi và nhận thông tin từ các chương trình khác bằng các lệnh giao thức HTTP như GET và POST.Mặc dù API REST hoạt động với hầu hết các giao thức, nhưng nó được thiết kế đặc biệt để truyền dữ liệu qua giao thức HTTP.an API that allows programmers to send and receive information from other programs using HTTP protocol commands such as GET and POST. Although REST API works with most protocols, it is specially designed for transmitting data through the HTTP protocol.

Chúng ta có thể phát triển ứng dụng bằng PHP không?

Bạn có thể không nghe hay không rằng bạn có thể sử dụng PHP cho phát triển ứng dụng Android của mình.Chúng tôi có thể sử dụng PHP làm back-end cho các ứng dụng Android của chúng tôi và tin tưởng tôi rằng họ làm việc hoàn hảo với nhau.Bất kỳ ứng dụng Android nào cần đăng nhập và đăng ký tài khoản đều có thể sử dụng hiệu quả PHP trên mặt sau của nó.. We can use PHP as the back-end for our Android Applications, and trust me they work flawlessly with each other. Any Android app that needs account log-in and registration can efficiently utilize PHP on its back-end.