Skip to content
最近公司在开发一款类似智能家居的硬件项目,需要内网和服务器做交互,同时也需要服务器去操作客户端硬件,考虑到服务器终端。各方面性能比较差,也不想用长连接,所以干脆在android设备上也跑了一个service 给服务端提供http接口来调用,所以封装了这个库,为了让后端人员能直接上手,所以配置方法,和注解,都模仿了SpringMVC
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.idea
app
gradle/wrapper
httplib
.gitignore
README.md
build.gradle
gradle.properties
gradlew
gradlew.bat
settings.gradle

README.md

ShAndroidHttpService

Android http服务器

Download the latest JAR or grab via Maven:

<dependency>
  <groupId>code.zsh.sh.com.shandroidhttpservice</groupId>
  <artifactId>httplib</artifactId>
  <version>1.0.0</version>
  <type>pom</type>
</dependency>

or Gradle:

compile 'code.zsh.sh.com.shandroidhttpservice:httplib:1.0.0'

启动http服务

    WebServer  webServer = new WebServer(PORT);
            //配置controller 集合
            webServer.setControllerName(getClassName(CONTROLLER));
            //配置拦截器 集合
            webServer.setInterceptPName(getClassName(INTERCEPTS));
            webServer.setDaemon(true);
            webServer.start();

ShInterceptor 拦截器

继承ShInterceptor 实现preHandle 和postHandle 方法 前着在收到请求前调用 后者在完成请求后调用

public class HttpIntercepts implements ShInterceptor {
    @Override
    public boolean preHandle(HttpRequest request, HttpResponse response, HttpContext context) {
        try {
            String target = URLDecoder.decode(request.getRequestLine().getUri(),
                    "UTF-8");

            Log.e("url=", target);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    @Override
    public void postHandle(HttpRequest request, HttpResponse response, HttpContext context) {

    }
}

Controller Action

@Controller

改controller的作用域,

@RequestMapping

调用的action 下面的写法最终生成的地址 xxx.xxx.xxx.xxx:xxxx/api/getphoneinof 返回值以json类型返回

@Controller(space = "/api")
public class HttpController {
 
    @RequestMapping(path = "/getphoneinof")
    public ResultModel getPhoneInof()  {
         ResultModel resultModel = new ResultModel(true);
        return resultModel;
    }
}

传递参数

在方法的前面加上@Requestparam 即可

   @RequestMapping(path = "/toast")
    public ResultModel toast(@Requestparam("message") String message)  {
        ResultModel resultModel = new ResultModel(true);
        MainActivity.mainActivity.toast(message);
        return resultModel;
    }
You can’t perform that action at this time.