当前位置:   article > 正文

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

andserver
项目中引用AndServer
implementation 'com.yanzhenjie.andserver:api:2.1.10'
  • 1

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

buildscript {
    repositories {
        mavenCentral()
    }
 
    dependencies {
        classpath 'com.yanzhenjie.andserver:plugin:2.1.10'
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
在当前的moudle(一般就是app)的build.gradle里面的plugins里面添加:
id 'com.yanzhenjie.andserver'
  • 1
plugins
plugins {
    id 'com.android.application'
    id 'com.yanzhenjie.andserver'
}
  • 1
  • 2
  • 3
  • 4
build.gradle里面dependencies的添加
    implementation 'com.yanzhenjie.andserver:api:2.1.10'
    annotationProcessor 'com.yanzhenjie.andserver:processor:2.1.10'
  • 1
  • 2
代码
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();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58

以上代码启动在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;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
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;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
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"/>
  • 1
  • 2
  • 3
测试
  • get测试
    在这里插入图片描述
  • post测试
  • 在这里插入图片描述
    可结合https://blog.csdn.net/zyc3545/article/details/109150010此篇文章合并到一块
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/煮酒与君饮/article/detail/780081
推荐阅读
相关标签
  

闽ICP备14008679号