基於AndroidAsync框架搭建Android Http Server

一、庫簡介


    implementation 'com.koushikdutta.async:androidasync:2.2.1' // Http Server

源碼github地址:https://github.com/koush/AndroidAsync

二、代碼分享

1、HttpService.java(服務類)

package com.interjoy.utils.serviceutils;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

/**
 * @author: cwang Interjoy
 * @time: 2020/3/1114:55
 * @Description:MyHttpServer的服務
 */
public class HttpService extends Service {

    public HttpService(){

    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        MyHttpServer.getInstance().start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        MyHttpServer.getInstance().stop();
    }
}

2、MyHttpServer.java(Http Server類)

package com.interjoy.utils.serviceutils;

import android.util.Log;

import com.interjoy.utils.systemutils.AccessInfo;
import com.koushikdutta.async.http.body.AsyncHttpRequestBody;
import com.koushikdutta.async.http.server.AsyncHttpServer;
import com.koushikdutta.async.http.server.AsyncHttpServerRequest;
import com.koushikdutta.async.http.server.AsyncHttpServerResponse;
import com.koushikdutta.async.http.server.HttpServerRequestCallback;

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

/**
 * @author: cwang 
 * @time: 2020/3/11 15:01
 * @Description:HttpServer
 */
public class MyHttpServer implements HttpServerRequestCallback {
    private static final String TAG = "MyHttpServer";
    private static MyHttpServer mInstance;
    private static int PORT_DEFALT = 12020; // 監聽端口號
    private static String ERRORCODE = "error_code"; // error_code
    private static String ERRORMSG = "error_msg"; // error_msg
    private static String COMPANYKEY = "cwang.com"; // 公司Key
    private static String SECRET = "xxxxx"; // 祕鑰

    AsyncHttpServer mServer = new AsyncHttpServer();

    public static MyHttpServer getInstance() {
        if (mInstance == null) {
            synchronized (MyHttpServer.class) {
                if (mInstance == null) {
                    mInstance = new MyHttpServer();
                }
            }
        }
        return mInstance;
    }

    /**
     * 開始監聽端口
     */
    public void start() {
        Log.d(TAG, "Starting http server...");
        mServer.get("[\\d\\D]*", this);
        mServer.post("[\\d\\D]*", this);
        mServer.listen(PORT_DEFALT);
    }

    /**
     * 停止監聽端口
     */
    public void stop() {
        Log.d(TAG, "Stopping http server...");
        mServer.stop();
    }

    /**
     * 發送響應信息給Client端
     *
     * @param response
     * @param json
     */
    private void sendResponse(AsyncHttpServerResponse response, JSONObject json) {
        // Enable CORS
        response.getHeaders().add("Access-Control-Allow-Origin", "*");
        response.send(json);
    }

    @Override
    public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
        String uri = request.getPath();
        Log.d(TAG, "onRequest " + uri);

        Object params = null;
        if (request.getMethod().equals("POST")) {
            String contentType = request.getHeaders().get("Content-Type"); // Content-Type
            String authorization = request.getHeaders().get("Authorization"); // 鑑權串
            Log.i(TAG, "authorization == " + authorization);

            // 驗證Content-Type
            if (!contentType.equals("application/json")) {
                Log.e(TAG, "Headers Content-Type Error");
                handleInvalidContentTypeRequest(params, response);
                return;
            }

            // 驗證鑑權
            int keyIndex = authorization.indexOf(COMPANYKEY); // 公司key下標
            if (keyIndex <= 0) { // 截取出明文、SHA256串
                Log.e(TAG, "Headers Authorization Error");
                handleInvalidAuthorizationRequest(params, response);
                return;
            }
            String plainTextSignatureStr = authorization.substring(keyIndex);
            Log.i(TAG, "plainTextSignatureStr == " + plainTextSignatureStr);
            String sha256 = authorization.substring(0, keyIndex);
            Log.i(TAG, "sha256 == " + sha256);
            String key_signatureStr = SECRET + plainTextSignatureStr; // 祕鑰+明文
            Log.i(TAG, "key_signatureStr 明文== " + key_signatureStr);
            String shaStr = new SHA256Encrypt().bin2hex(key_signatureStr); // SHA256算法加密
            Log.i(TAG, "mAuthorization sha == " + shaStr);
            if (!sha256.equals(shaStr)) { // 授權失敗
                Log.e(TAG, "Headers Authorization Error");
                handleInvalidAuthorizationRequest(params, response);
                return;
            }
            params = ((AsyncHttpRequestBody<JSONObject>) request.getBody()).get();
        } else {
            Log.e(TAG, "Unsupported RequestProtocol");
            handleInvalidUnsupportedRequestProtocolRequest(params, response);
            return;
        }

        if (params != null) {
            Log.d(TAG, "params = " + params.toString());
        }

        // 解析API
        switch (uri) {
            case "/getDeviceInfo": // 獲取設備信息
                handleDeviceInfoRequest(params, response);
                break;
            
            default: // 無效API請求
                handleInvalidRequest(params, response);
                break;
        }
    }

    /**
     * 獲取設備信息
     *
     * @param params   請求參數
     * @param response
     */
    private void handleDeviceInfoRequest(Object params, AsyncHttpServerResponse response) {
        // Send JSON format response
        try {
            JSONObject json = new JSONObject();
            json.put("SystemModel", AccessInfo.getSystemModel());
            json.put("DeviceSN", AccessInfo.getDeviceSN());
            json.put("DeviceName", AccessInfo.getDeviceName());
            json.put("SystemVersion", AccessInfo.getSystemVersion());
            json.put("SoftVersion", AccessInfo.getSoftVersion());
            sendResponse(response, json);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    /**
     * 無效請求
     *
     * @param params
     * @param response
     */
    private void handleInvalidRequest(Object params, AsyncHttpServerResponse response) {
        JSONObject json = new JSONObject();
        try {
            json.put("error", "InvalidAPI");
            sendResponse(response, json);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 請求的Content-Type不對
     *
     * @param params
     * @param response
     */
    private void handleInvalidContentTypeRequest(Object params, AsyncHttpServerResponse response) {
        JSONObject json = new JSONObject();
        try {
            json.put("error", "ContentType");
            sendResponse(response, json);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 請求的Authorization不對
     *
     * @param params
     * @param response
     */
    private void handleInvalidAuthorizationRequest(Object params, AsyncHttpServerResponse response) {
        JSONObject json = new JSONObject();
        try {
            json.put("error", "Authorization");
            sendResponse(response, json);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    /**
     * 請求協議不對
     *
     * @param params
     * @param response
     */
    private void handleInvalidUnsupportedRequestProtocolRequest(Object params, AsyncHttpServerResponse response) {
        JSONObject json = new JSONObject();
        try {
            json.put("error", "UnsupportedRequestProtocol");
            sendResponse(response, json);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

3、AndroidManifest.xml(註冊服務)

<service
    android:name="com.interjoy.utils.serviceutils.HttpService"
    android:enabled="true"
    android:exported="true" />

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章