cordova整合NanoHTTPD实现APP对外提供接口服务

1、创建cordova项目

  • 创建项目
cordova create nano-test com.liang.nano nanoTest
  • 添加android平台
cordova platforms add android

2、添加NanoHTTPD

{项目目录}\nano-test\platforms\android\app\build.gradle

dependencies{} 内添加

//nanohttpd
implementation 'org.nanohttpd:nanohttpd:2.3.1'

3、实现服务

新建HttpServer 继承 NanoHTTPD ,serve(IHTTPSession session)方法为所有请求的入口

package com.liang.nano;

import android.content.Context;

import org.apache.cordova.LOG;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import fi.iki.elonen.NanoHTTPD;

public class HttpServer extends NanoHTTPD {

    public static String TAG = "HttpServer";

    private Context mContext;

    public HttpServer(int port) {
        super(port);
    }

    public HttpServer(int port,Context mContext) {
        super(port);
        this.mContext = mContext;
    }

      // 所有请求的入口
    @Override
    public Response serve(IHTTPSession session) {
        int code = 1;
        String msg = "success";
        String uri = session.getUri();
        String method = session.getMethod().toString();
        String queryParameterString = session.getQueryParameterString();
        Map<String,String> body = new HashMap<>();

        try {
            session.parseBody(body);
        } catch (IOException | ResponseException e) {
            code = 0;
            msg = "body to JSON fail";
            LOG.e(TAG,msg,e);
        }

        Map<String,Object> result = new HashMap<>();
        result.put("code",code);
        result.put("msg",msg);
        result.put("body",body);
        result.put("uri",uri);
        result.put("method",method);
        result.put("queryParameterString",queryParameterString);

        JSONObject jsonObject = new JSONObject(result);

        return newFixedLengthResponse(Response.Status.OK,"application/json",jsonObject.toString());
    }
}

4、修改cordova的MainActivity

增加/* HttpServer start /与/ HttpServer end */之间的内容

package com.liang.nano;

import android.os.Bundle;
import org.apache.cordova.*;

import java.io.IOException;

public class MainActivity extends CordovaActivity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        // enable Cordova apps to be started in the background
        Bundle extras = getIntent().getExtras();
        if (extras != null && extras.getBoolean("cdvStartInBackground", false)) {
            moveTaskToBack(true);
        }

        /* HttpServer start */
        try {
            // 监听端口9100
            HttpServer httpServer = new HttpServer(9100,this);
            // 服务启动
            httpServer.start();
        } catch (IOException e) {
            LOG.e(TAG,"HttpServer start fail",e);
        }
        /* HttpServer end */

        // Set by <content src="index.html" /> in config.xml
        loadUrl(launchUrl);
    }
}

5.编译打包成apk并安装

6.测试

1.手机测试

  • 启动APP
  • 不要关闭APP,切换到后台,打开手机浏览器
  • 浏览器地址栏访问
http://127.0.0.1:9100/api/test?userId=sylmj
  • 浏览器页面得到响应
["body":{},"msg":"success","uri":"\/api\/test","queryParameterString":null,"code":1}

2.安卓模拟器测试

问题处理

1)android studio识别不到模拟器设备

  • 启动Android Studio
  • 启动夜神模拟器
  • 找到自己Android Studio使用的SDK对应的文件夹,找到platform-tools文件夹,比如我的在D:\SDK\platform-tools。
  • 在这个目录下启动cmd命令窗口,执行下面命令

夜神模拟器:

adb connect 127.0.0.1:62001

mumu模拟器:

adb connect 127.0.0.1:7555

2)获取局域网的ip地址

我使用的是夜神模拟器,需要将网络设置改成桥接模式

系统设置-手机-网络设置-勾选 桥接模式-IP模式 勾选DHCP

上面显示的IP地址即为模拟器的局域网IP地址,我的为192.168.0.101

测试

  • 浏览器地址栏访问
http://192.168.0.101:9100/api/test?userId=sylmj
  • 浏览器页面得到响应,与手机本机测试效果一致
["body":{},"msg":"success","uri":"\/api\/test","queryParameterString":null,"code":1}
  • postman发送POST请求

  • 地址

http://192.168.0.101:9100/api/test?userId=sylmj
  • 请求体
{
    "zjhm":"123"
}
  • 响应
{
    "body": {
        "postData": "{\r\n    \"zjhm\":\"123\"\r\n}"
    },
    "method": "POST",
    "msg": "success",
    "uri": "/api/test",
    "queryParameterString": "userId=sylmj",
    "code": 1
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容