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>
// 实现效果如下: