public class HttpServer extends NanoHTTPD {
private static final String TAG = "HttpServer";
public static final String DEFAULT_SHOW_PAGE = "index.html";
public static final int DEFAULT_PORT = 9511;//此参数随便定义,最好定义1024-65535;1-1024是系统常用端口,1024-65535是非系统端口
public enum Status implements Response.IStatus {
REQUEST_ERROR(500, "请求失败"),
REQUEST_ERROR_API(501, "无效的请求接口"),
REQUEST_ERROR_CMD(502, "无效命令");
private final int requestStatus;
private final String description;
Status(int requestStatus, String description) {
this.requestStatus = requestStatus;
this.description = description;
}
@Override
public String getDescription() {
return description;
}
@Override
public int getRequestStatus() {
return requestStatus;
}
}
public HttpServer() {//初始化端口
super(DEFAULT_PORT);
}
@Override
public Response serve(IHTTPSession session) {
String uri = session.getUri();
Map<String, String> headers = session.getHeaders();
//接收不到post参数的问题, http://blog.csdn.net/obguy/article/details/53841559
try {
session.parseBody(new HashMap<String, String>());
} catch (IOException e) {
e.printStackTrace();
} catch (ResponseException e) {
e.printStackTrace();
}
Map<String, String> parms = session.getParms();
try {
LogUtil.d(TAG, uri);
//判断uri的合法性,自定义方法,这个是判断是否是接口的方法
if (checkUri(uri)) {
// 针对的是接口的处理
if (headers != null) {
LogUtil.d(TAG, headers.toString());
}
if (parms != null) {
LogUtil.d(TAG, parms.toString());
}
if (StringUtil.isEmpty(uri)) {
throw new RuntimeException("无法获取请求地址");
}
if (Method.OPTIONS.equals(session.getMethod())) {
LogUtil.d(TAG, "OPTIONS探测性请求");
return addHeaderResponse(Response.Status.OK);
}
switch (uri) {
case "/test": {//接口2
//此方法包括了封装返回的接口请求数据和处理异常以及跨域
return getXXX(parms);
}
default: {
return addHeaderResponse(Status.REQUEST_ERROR_API);
}
}
} else {
//针对的是静态资源的处理
String filePath = getFilePath(uri); // 根据url获取文件路径
if (filePath == null) {
LogUtil.d(TAG, "sd卡没有找到");
return super.serve(session);
}
File file = new File(filePath);
if (file != null && file.exists()) {
LogUtil.d(TAG, "file path = " + file.getAbsolutePath());
//根据文件名返回mimeType: image/jpg, video/mp4, etc
String mimeType = getMimeType(filePath);
Response res = null;
InputStream is = new FileInputStream(file);
res = newFixedLengthResponse(Response.Status.OK, mimeType, is, is.available());
//下面是跨域的参数(因为一般要和h5联调,所以最好设置一下)
response.addHeader("Access-Control-Allow-Headers", allowHeaders);
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, HEAD");
response.addHeader("Access-Control-Allow-Credentials", "true");
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Max-Age", "" + 42 * 60 * 60);
return res;
} else {
LogUtil.d(TAG, "file path = " + file.getAbsolutePath() + "的资源不存在");
}
}
} catch (Exception e) {
e.printStackTrace();
}
//自己封装的返回请求
return addHeaderRespose(Status.REQUEST_ERROR);
}
/**
* 开启本地网页点歌的服务
*/
public static void startLocalChooseMusicServer() {
if (httpServer == null) {
httpServer = new HttpServer();
}
try {
// 启动web服务
if (!httpServer.isAlive()) {
httpServer.start();
}
Log.i(TAG, "The server started.");
} catch (Exception e) {
httpServer.stop();
Log.e(TAG, "The server could not start. e = " + e.toString());
}
}
/**
* 关闭本地服务
*/
public static void quitChooseMusicServer() {
if (httpServer != null) {
if (httpServer.isAlive()) {
httpServer.stop();
Log.d(TAG, "关闭局域网点歌的服务");
}
}
}
dependencies {
compile 'com.koushikdutta.async:androidasync:2.2.1'
}
public class NIOHttpServer implements HttpServerRequestCallback {
private static final String TAG = "NIOHttpServer";
private static NIOHttpServer mInstance;
public static int PORT_LISTEN_DEFALT = 5000;
AsyncHttpServer server = new AsyncHttpServer();
public static NIOHttpServer getInstance() {
if (mInstance == null) {
// 增加类锁,保证只初始化一次
synchronized (NIOHttpServer.class) {
if (mInstance == null) {
mInstance = new NIOHttpServer();
}
}
}
return mInstance;
}
//仿照nanohttpd的写法
public static enum Status {
REQUEST_OK(200, "请求成功"),
REQUEST_ERROR(500, "请求失败"),
REQUEST_ERROR_API(501, "无效的请求接口"),
REQUEST_ERROR_CMD(502, "无效命令"),
REQUEST_ERROR_DEVICEID(503, "不匹配的设备ID"),
REQUEST_ERROR_ENV(504, "不匹配的服务环境");
private final int requestStatus;
private final String description;
Status(int requestStatus, String description) {
this.requestStatus = requestStatus;
this.description = description;
}
public String getDescription() {
return description;
}
public int getRequestStatus() {
return requestStatus;
}
}
/**
* 开启本地服务
*/
public void startServer() {
//如果有其他的请求方式,例如下面一行代码的写法
server.addAction("OPTIONS", "[\d\D]*", this);
server.get("[\d\D]*", this);
server.post("[\d\D]*", this);
server.listen(PORT_LISTEN_DEFALT);
}
@Override
public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
Log.d(TAG, "进来了,哈哈");
String uri = request.getPath();
//这个是获取header参数的地方,一定要谨记哦
Multimap headers = request.getHeaders().getMultiMap();
if (checkUri(uri)) {// 针对的是接口的处理
//注意:这个地方是获取post请求的参数的地方,一定要谨记哦
Multimap parms = (( AsyncHttpRequestBody<Multimap>)request.getBody()).get();
if (headers != null) {
LogUtil.d(TAG, headers.toString());
}
if (parms != null) {
LogUtil.d(TAG, "parms = " + parms.toString());
}
if (StringUtil.isEmpty(uri)) {
throw new RuntimeException("无法获取请求地址");
}
if ("OPTIONS".toLowerCase().equals(request.getMethod().toLowerCase())) {
LogUtil.d(TAG, "OPTIONS探测性请求");
addCORSHeaders(Status.REQUEST_OK, response);
return;
}
switch (uri) {
case "/test": {//接口2
//此方法包括了封装返回的接口请求数据和处理异常以及跨域
return getXXX(parms);
}
default: {
return addHeaderResponse(Status.REQUEST_ERROR_API);
}
}
} else {
// 针对的是静态资源的处理
String filePath = getFilePath(uri); // 根据url获取文件路径
if (filePath == null) {
LogUtil.d(TAG, "sd卡没有找到");
response.send("sd卡没有找到");
return;
}
File file = new File(filePath);
if (file != null && file.exists()) {
Log.d(TAG, "file path = " + file.getAbsolutePath());
response.sendFile(file);//和nanohttpd不一样的地方
} else {
Log.d(TAG, "file path = " + file.getAbsolutePath() + "的资源不存在");
}
}
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有