我是靠谱客的博主 自然小懒猪,最近开发中收集的这篇文章主要介绍android 简单实现Http交互,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

android 创建一个http交互的服务器
1、创建一个http请求类
2、创建一个service启动http

一、http类:创建一个继承NanoHTTPD 的类

//		所需依赖
    implementation 'org.nanohttpd:nanohttpd:2.2.0'
import fi.iki.elonen.NanoHTTPD;
public class HTTPServer extends NanoHTTPD {

    public HTTPServer (int port) {
        super(port);
    }
    @Override
    public Response serve(IHTTPSession session) {

        Map<String, String> files = new HashMap<>();
        //  用于接收请求的返回值Bean
        Bean bean;
        Gson gson = new Gson();
        try {
            session.parseBody(files);
            String callBack = files.get("postData");
            RingLog.e(callBack);
        } catch (Exception e) {
            RingLog.e(e.toString());
        }
        StringBuilder builder = new StringBuilder();
        Method method = session.getMethod();
        String uri = session.getUri();
        RingLog.i("uri:"+uri);
        builder.append("yw");// 反馈给调用者的数据
        Map<String, String> parms = session.getParms();
        String data = "";
        if (method.name().equals("POST")){
            Map<String, String> header = session.getHeaders();
            data = files.get("postData");
        }else {
            for (String key : parms.keySet()) {
                RingLog.e("key= "+key);
                data = key;
            }
        }
        RingLog.e("uri: " + uri);//如果有uri,会打印出uri
        //这里的data是POST提交表单时key
        RingLog.e("data: " + data);//如果有data,会打印出data

//			这里是判断请求路径中是否需要加入Uri,如果不需要,则可以取消这个判断
        if(uri.contains("ytxs")) {
            try {
                bean= gson.fromJson(data, Bean.class);
            } catch (Exception e) {
                return newFixedLengthResponse(gson.toJson(new YintiCallBackBean("failed", "数据类型错误")));
            }

            if (bean== null) {
                return newFixedLengthResponse(gson.toJson(new YintiCallBackBean("failed", "数据错误")));
            }
        }else {
        	return newFixedLengthResponse(gson.toJson(new YintiCallBackBean("failed", "请求路径错误")));
        }
        //响应信息
        return newFixedLengthResponse(gson.toJson(new YintiCallBackBean("success","")));
    }
}

二、service :

public class ServerService extends Service {

    private HTTPServer jsonHandlerNano;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (jsonHandlerNano != null) {
            try {
                jsonHandlerNano.stop();
                ServerPresenter.onServerStopped(ServerService.this);
            } catch (Exception e) {
                e.printStackTrace();
                ServerPresenter.onServerError(ServerService.this, "停止服务错误");
            }
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        jsonHandlerNano = new HTTPServer (8099);
        createNotificationChannel();
        try {
            Log.e("1", "开启服务");
            // 开启HTTP服务
            jsonHandlerNano.start();
            ServerPresenter.onServerStarted(ServerService.this, "");
        } catch (IOException e) {
            e.printStackTrace();
            ServerPresenter.onServerError(ServerService.this, e.toString());
        }
        return START_STICKY;
    }

    private void createNotificationChannel() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            // 通知渠道的id
            String id = "my_channel_01";
            // 用户可以看到的通知渠道的名字.
            CharSequence name = "网络服务";
//         用户可以看到的通知渠道的描述
            String description = "网络服务正在开启";
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = new NotificationChannel(id, name, importance);
            //         配置通知渠道的属性
            mChannel.setDescription(description);
         设置通知出现时的闪灯(如果 android 设备支持的话)
//            mChannel.enableLights(true); mChannel.setLightColor(Color.RED);
         设置通知出现时的震动(如果 android 设备支持的话)
//            mChannel.enableVibration(true);
//            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
//         最后在notificationmanager中创建该通知渠道 //
            mNotificationManager.createNotificationChannel(mChannel);

            // 为该通知设置一个id
            int notifyID = 1;
            // 通知渠道的id
            String CHANNEL_ID = "my_channel_01";
            // Create a notification and set the notification channel.
            Notification notification = new Notification.Builder(this)
                    .setContentTitle("提示").setContentText("网络服务已开启")
                    .setSmallIcon(R.drawable.ic_launcher_foreground)
                    .setChannelId(CHANNEL_ID)
                    .build();
            startForeground(1, notification);
        }else {
            Notification.Builder builder = new Notification.Builder(this.getApplicationContext()); //获取一个Notification构造器
            builder.setContentTitle("提示")
                    .setContentText("网络服务已开启"); // 设置上下文内容
            Notification notification = builder.build(); // 获取构建好的Notification
            notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
            startForeground(110, notification);// 开始前台服务
        }
    }
}

ServerPresenter:

public class ServerPresenter {

    private static final String ACTION_SERVER_CHANGE = "com.leavesc.androidserver.action_server_change";

    private static final String KEY_SERVER_STATE = "serverState";

    private static final String KEY_SERVER_MESSAGE = "serverMessage";

    private static final int VALUE_STARTED = 100;

    private static final int VALUE_STOPPED = 200;

    private static final int VALUE_ERROR = 300;
    //广播监听服务状态
    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int state = intent.getIntExtra(KEY_SERVER_STATE, 0);
            switch (state) {
                case VALUE_STARTED: {
                    if (serverChangeListener != null) {
                        serverChangeListener.onServerStarted(intent.getStringExtra(KEY_SERVER_MESSAGE));
                    }
                    break;
                }
                case VALUE_STOPPED: {
                    if (serverChangeListener != null) {
                        serverChangeListener.onServerStopped();
                    }
                    break;
                }
                case VALUE_ERROR: {
                    if (serverChangeListener != null) {
                        serverChangeListener.onServerError(intent.getStringExtra(KEY_SERVER_MESSAGE));
                    }
                    break;
                }
            }
        }
    };

    private OnServerChangeListener serverChangeListener;

    public ServerPresenter(Context context, OnServerChangeListener serverChangeListener) {
        context.registerReceiver(broadcastReceiver, new IntentFilter(ACTION_SERVER_CHANGE));
        this.serverChangeListener = serverChangeListener;
    }
    //启动服务
    public void startServer(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(new Intent(context, ServerService.class));
        }else{
            context.startService(new Intent(context, ServerService.class));
        }
    }
    //关闭服务
    public void stopServer(Context context) {
        context.stopService(new Intent(context, ServerService.class));
    }
    //释放资源
    public void unregister(Context context) {
        context.unregisterReceiver(broadcastReceiver);
        this.serverChangeListener = null;
    }

    public static void onServerStarted(Context context, String ipAddress) {
        Intent intent = new Intent(ACTION_SERVER_CHANGE);
        intent.putExtra(KEY_SERVER_STATE, VALUE_STARTED);
        intent.putExtra(KEY_SERVER_MESSAGE, ipAddress);
        context.sendBroadcast(intent);
    }

    public static void onServerStopped(Context context) {
        Intent intent = new Intent(ACTION_SERVER_CHANGE);
        intent.putExtra(KEY_SERVER_STATE, VALUE_STOPPED);
        context.sendBroadcast(intent);
    }

    public static void onServerError(Context context, String message) {
        Intent intent = new Intent(ACTION_SERVER_CHANGE);
        intent.putExtra(KEY_SERVER_STATE, VALUE_ERROR);
        intent.putExtra(KEY_SERVER_MESSAGE, message);
        context.sendBroadcast(intent);
    }

}

至此,就可以简单的实现一个http交互的功能了!!!

以上,如有不同见解,请评论区留言!!!

最后

以上就是自然小懒猪为你收集整理的android 简单实现Http交互的全部内容,希望文章能够帮你解决android 简单实现Http交互所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(62)

评论列表共有 0 条评论

立即
投稿
返回
顶部