使用Netty构建APP后台服务器实现http请求
来源:互联网 发布:手机号码筛选软件 编辑:程序博客网 时间:2024/05/29 17:09
APP通过Http请求后台服务器的关键是连接url,及返回参数。
在开发APP的过程中,会频繁的与后台服务器进行交互,当业务比较复杂的情况下,后台服务接口开发速度不见得会满足APP的调用,经过APP调用后台服务进行分析得出,可以通过设置url及返回数据两个参数进行后台服务器的配置。按照一定的配置规则,先模拟一个能够让APP能够跑起来的后台服务,实现APP的快速开发。
后台实现代码如下:
// 后台服务器代码,监听指定端口提供HTTP请求调用服务
public class AppServerMonitor implements Runnable {
private int port;
public AppServerMonitor(int port){
this.port = port;
}
public void run() {
// TODO Auto-generated method stub
EventLoopGroup acceptorGroup = new NioEventLoopGroup();
EventLoopGroup clientGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBookstrap = new ServerBootstrap();
serverBookstrap.group(acceptorGroup, clientGroup).channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 100)
.childHandler(new ChannelInitializer<SocketChannel>(){
protected void initChannel(SocketChannel sc) throws Exception {
sc.pipeline().addLast("http-decoder",new HttpRequestDecoder());
sc.pipeline().addLast("http-aggregator",new HttpObjectAggregator(64*1024));
sc.pipeline().addLast("http-encoder",new HttpResponseEncoder());
sc.pipeline().addLast("http-handler",new UrlHandler());
}
});
ChannelFuture channelFuture = serverBookstrap.bind(port).sync();
channelFuture.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
acceptorGroup.shutdownGracefully();
clientGroup.shutdownGracefully();
}
}
public static void main(String[] args){
// url数据模拟器 可以从数据库进行配置 配置
ResponseMap.setResponse("/abcd", "{\"aa\":\"abcde\"}");
ResponseMap.setResponse("/dcba", "{\"aa\":\"dcba\"}");
//
String url = "****";
String values="******";
ResponseMap.setResponse(url , values}");
new AppServerMonitor(8080).run();
}
}
// netty解码器
public class UrlHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
@Override
protected void messageReceived(ChannelHandlerContext ctx,
FullHttpRequest req) throws Exception {
// TODO Auto-generated method stub
//解码不成功
if(!req.getDecoderResult().isSuccess())
{
sendErrorToClient(ctx,HttpResponseStatus.BAD_REQUEST);
return ;
}
if(req.getMethod().compareTo(HttpMethod.GET)!=0){
sendErrorToClient(ctx,HttpResponseStatus.METHOD_NOT_ALLOWED);
return;
}
String uri=req.getUri();
String value = ResponseMap.getResponse(uri);
sendValuesClient(ctx,value);
}
private void sendValuesClient(ChannelHandlerContext ctx, String value) throws Exception {
ByteBuf buffer=Unpooled.copiedBuffer(value.getBytes());
FullHttpResponse resp=new DefaultFullHttpResponse(HTTP_1_1,HttpResponseStatus.OK,buffer);
MimetypesFileTypeMap mimeTypeMap=new MimetypesFileTypeMap();
resp.headers().set("CONTENT-TYPE", "UTF-8");
ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);
}
public static final HttpVersion HTTP_1_1 = new HttpVersion("HTTP", 1, 1, true);
private static final String CRLF = "\r\n";
private void sendErrorToClient(ChannelHandlerContext ctx,
HttpResponseStatus status) throws UnsupportedEncodingException {
ByteBuf buffer=Unpooled.copiedBuffer(("系统服务出错:"+status.toString()+CRLF).getBytes("utf-8"));
FullHttpResponse resp=new DefaultFullHttpResponse(HTTP_1_1,status,buffer);
resp.headers().set("Content-Type", "text/html;charset=utf-8");
ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);
}
}
// 连接,返回值容器自定义一个静态Map用于存储
public class ResponseMap {
private static Map<String, String> responseMap = new HashMap<String, String>();
public static void setResponse(String url, String value){
responseMap.put(url, value);
}
/**
* 默认返回
* @param url
* @return
*/
public static String getResponse(String url){
String value = responseMap.get(url);
if (null == value){
value = "{success:0}";
}
return value;
}
}
//对于静态MAP 也可以使用数据库进行url + values 存储
// maven 配置
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>5.0.0.Alpha1</version>
</dependency>
// 实现效果如下:
- 使用Netty构建APP后台服务器实现http请求
- 使用netty构建http服务器
- netty实现http服务器
- 使用MUI框架构建App请求http接口实例
- Netty实现简单HTTP服务器
- 使用Netty搭建APP推送服务器
- 用Netty实现的简单HTTP服务器
- 用Netty实现的简单HTTP服务器
- 用Netty实现的简单HTTP服务器
- Play框架的Netty Http服务器实现
- Java-->使用netty搭建Http服务器
- [Android]通过JNI实现卸载自身App后台发送Http请求~
- [Android]通过JNI实现卸载自身App后台发送Http请求~
- 使用Vue构建Ionic混合APP系列教程(三):服务和Http请求
- netty服务器搭建-http
- netty整合springMVC,实现高效的HTTP服务请求
- 使用Netty构建一个多线程服务器与客户端
- android APP实现更新 PHP后台服务器
- 在CentOS下安装Pygame
- MPI 安装
- 1234567转成一百二十三万四千五百六十七
- 编译安装MySQL-5.5
- 嵌入式视频方案学习第十三篇——音频模块AUDIO
- 使用Netty构建APP后台服务器实现http请求
- 使用 xcworkspace 管理 iOS 工程
- USB 全速/高速设备识别信号分析
- Linux进程间通信——使用匿名管道
- 命令模式
- Ubuntu16.04 ibus-pinyin安装
- 基本数据类型和引用数据类型的区别:
- saltsack开启自动认证
- Markdown--从入门到精通(md源文件)