Android设备搭建http服务---------AndServer

10 篇文章 0 订阅
4 篇文章 0 订阅
项目中引用AndServer
implementation 'com.yanzhenjie.andserver:api:2.1.10'

在项目的根build.gradle文件(不是app那个moudle的build.gradle)最顶部添加:

buildscript {
    repositories {
        mavenCentral()
    }
 
    dependencies {
        classpath 'com.yanzhenjie.andserver:plugin:2.1.10'
    }
}
在当前的moudle(一般就是app)的build.gradle里面的plugins里面添加:
id 'com.yanzhenjie.andserver'
plugins
plugins {
    id 'com.android.application'
    id 'com.yanzhenjie.andserver'
}
build.gradle里面dependencies的添加
    implementation 'com.yanzhenjie.andserver:api:2.1.10'
    annotationProcessor 'com.yanzhenjie.andserver:processor:2.1.10'
代码
package com.dzdpencrypt.dzdp;
 
import androidx.appcompat.app.AppCompatActivity;
 
import android.os.Bundle;
 
import com.yanzhenjie.andserver.AndServer;
import com.yanzhenjie.andserver.Server;
 
import java.util.concurrent.TimeUnit;
 
public class MainActivity extends AppCompatActivity {
    private Server mServer;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (!isServiceRunning(getApplicationContext(), KeepAliveService.class)) {
            Log.d(LOG_TAG, "检测到服务未在运行,启动服务");
            serviceIntent = new Intent(this, KeepAliveService.class);
            startService(serviceIntent);
        } else {
            Log.d(LOG_TAG, "检测到服务正在运行,无需再次启动");
        }
        
        TextView textView = findViewById(R.id.ipsd);   # 绑定textview的相关id
        textView.setText(NetUtils.getLocalIPAddress().getHostAddress() + ":9999");   # app中textview显示ip+端口
        mServer = AndServer.webServer(this)
                .port(9999)
                .timeout(10, TimeUnit.SECONDS).listener(new Server.ServerListener() {
                    @Override
                    public void onStarted() {

                        System.out.println("服务器绑定地址:"+NetUtils.getLocalIPAddress().getHostAddress());
                    }

                    @Override
                    public void onStopped() {

                    }

                    @Override
                    public void onException(Exception e) {

                    }
                })
                .build();

        mServer.startup();
    }
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mServer.shutdown();
    }
}

以上代码启动在Android手机(设备)上的http服务器,服务器绑定端口9999

spring样式的restful代码实现
package com.dzdpencrypt.service;
 
import com.yanzhenjie.andserver.annotation.GetMapping;
import com.yanzhenjie.andserver.annotation.PathVariable;
import com.yanzhenjie.andserver.annotation.PostMapping;
import com.yanzhenjie.andserver.annotation.QueryParam;
import com.yanzhenjie.andserver.annotation.RequestBody;
import com.yanzhenjie.andserver.annotation.RequestParam;
import com.yanzhenjie.andserver.annotation.RestController;
 
import org.json.JSONObject;
 
 
@RestController
public class ServerController {
    @GetMapping("/")
    public String ping() {
        return "SERVER OK";
    }
 
    @PostMapping("/user/login")
    public JSONObject login(@RequestBody String str) throws Exception {
        JSONObject jsonObject = new JSONObject(str);
        return jsonObject;
    }
 
    @GetMapping("/user/item")
    public JSONObject requestItem(@RequestParam("name") String name,
                                 @RequestParam("id") String id) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", name);
        jsonObject.put("id", id);
 
        return jsonObject;
    }
 
    @GetMapping("/user/{userId}")
    public JSONObject getUser(@PathVariable("userId") String userId,
                           @QueryParam("key") String key) throws Exception{
        JSONObject user = new JSONObject();
        user.put("id", userId);
        user.put("key", key);
        user.put("year", 2022);
 
        return user;
    }
}
NetUtils.java-------获取当前Android手机的IP地址
package com.dzdpencrypt.service;
 
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.regex.Pattern;
 
public class NetUtils {
    private static final Pattern IPV4_PATTERN = Pattern.compile(
            "^(" + "([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}" +
                    "([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
 
    public static boolean isIPv4Address(String input) {
        return IPV4_PATTERN.matcher(input).matches();
    }
 
    public static InetAddress getLocalIPAddress() {
        Enumeration<NetworkInterface> enumeration = null;
        try {
            enumeration = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        if (enumeration != null) {
            while (enumeration.hasMoreElements()) {
                NetworkInterface nif = enumeration.nextElement();
                Enumeration<InetAddress> inetAddresses = nif.getInetAddresses();
                if (inetAddresses != null) {
                    while (inetAddresses.hasMoreElements()) {
                        InetAddress inetAddress = inetAddresses.nextElement();
                        if (!inetAddress.isLoopbackAddress() && isIPv4Address(inetAddress.getHostAddress())) {
                            return inetAddress;
                        }
                    }
                }
            }
        }
        return null;
    }
}
AndroidManifest.xml配置网络权限
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
测试
  • get测试
    在这里插入图片描述
  • post测试
  • 在这里插入图片描述
    可结合https://blog.csdn.net/zyc3545/article/details/109150010此篇文章合并到一块
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

༒࿈十三༙྇࿈༒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值