mac
2024-01-19 be5c9f324ac1d31f4f262d288c5f72a7a0c10c47
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
package com.hdl.photovoltaic.internet.HttpServer;
 
import android.text.TextUtils;
 
import com.alibaba.fastjson.JSON;
import com.hdl.photovoltaic.other.HdlFileLogic;
import com.hdl.photovoltaic.other.HdlLogLogic;
 
 
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import fi.iki.elonen.NanoHTTPD;
 
/**
 * 本地服务
 */
public class MyNanoHttpServer extends NanoHTTPD {
 
    //声明服务端 端口
    public static Integer HTTP_PORT = 49152;// 46219;
 
    public MyNanoHttpServer(String hostname, int port) {
        super(hostname, port);
    }
 
    private volatile static MyNanoHttpServer myNanoHttpServer;
 
    //TODO    单例模式,获取实例对象,并传入当前机器IP
    public static MyNanoHttpServer getInstance(String ipAddress) {
        if (myNanoHttpServer == null) {
            synchronized (MyNanoHttpServer.class) {
                if (myNanoHttpServer == null) {
                    myNanoHttpServer = new MyNanoHttpServer(ipAddress, HTTP_PORT);
                }
            }
        }
        return myNanoHttpServer;
    }
 
 
    @Override
    public Response serve(IHTTPSession session) {
        //TODO  解决客户端请求参数携带中文,出现中文乱码问题
        ContentType ct = new ContentType(session.getHeaders().get("content-type")).tryUTF8();
        session.getHeaders().put("content-type", ct.getContentTypeHeader());
        return dealWith(session);
 
    }
 
 
    private Response dealWith(IHTTPSession session) {
        Date dateTime = new Date();
        if (Method.POST == session.getMethod()) {
            //todo POST方法
            //获取请求头数据
            Map<String, String> header = session.getHeaders();
            //获取传参参数
            Map<String, String> params = new HashMap<String, String>();
            try {
                session.parseBody(params);
                String paramStr = params.get("postData");
                //响应客户端
                return newFixedLengthResponse("success");
            } catch (IOException | ResponseException e) {
                e.printStackTrace();
            }
            return newFixedLengthResponse("success");
        } else if (Method.GET == session.getMethod()) {
            //todo GET方法
            Map<String, List<String>> parameters = session.getParameters();
            //驱动升级文件路径
            String fileName = ((HTTPSession) session).getUri();
            if (!TextUtils.isEmpty(fileName)) {
                if (fileName.contains(HdlFileLogic.getInstance().getDriveRootPath())
                        || fileName.contains(HdlFileLogic.getInstance().getFirmwareRootPath())) {
                    String range = session.getHeaders().get("range");
                    if (TextUtils.isEmpty(range)) {
                        return newFixedLengthResponse("错误,头部没有range字段(-500)");
                    }
                    HdlLogLogic.print("http逆变器请求===请求大小-->" + range, true);
                    if (!range.contains("=")) {
                        HdlLogLogic.print("错误,range的value格式不对.(-501)", true);
                        return newFixedLengthResponse("错误,range的value格式不对.(-501)");
                    }
                    String[] bytesAry = range.split("=");
                    if (bytesAry.length < 2) {
                        HdlLogLogic.print("错误,range的value格式不对.(-502)", true);
                        return newFixedLengthResponse("错误,range的value格式不对.(-502)");
                    }
                    String[] dataIndex = bytesAry[1].split("-");
                    if (dataIndex.length < 2) {
                        HdlLogLogic.print("错误,range的value格式不对.(-503)", true);
                        return newFixedLengthResponse("错误,range的value格式不对.(-503)");
                    }
                    int startIndex = Integer.parseInt(dataIndex[0]);
                    int endIndex = Integer.parseInt(dataIndex[1]);
                    if (endIndex + 1 - startIndex <= 0) {
                        HdlLogLogic.print("错误,请求大小有问题.(-504)", true);
                        return newFixedLengthResponse("错误,请求大小有问题.(-504)");
                    }
                    //读取本地文件字节流
                    byte[] sourceDataByte = HdlFileLogic.getInstance().readFileByte(fileName);
                    if (sourceDataByte == null || sourceDataByte.length == 0) {
                        HdlLogLogic.print("错误,本地找不到文件,请下载再试.(-505)", true);
                        return newFixedLengthResponse("错误,本地找不到文件,请下载再试.(-505)");
                    }
                    //根据请求大小创建缓存区
                    byte[] newByte = new byte[endIndex - startIndex + 1];
                    //根据请求偏移量取数据,且复制到缓存区
                    System.arraycopy(sourceDataByte, startIndex, newByte, 0, endIndex + 1 - startIndex);
                    //响应客户端
                    Response response = newFixedLengthResponse(newByte);
                    response.addHeader("Content-Range", range + "/" + sourceDataByte.length);//伟南需要这个字段
                    HdlLogLogic.print("http回复数据===请求大小-->" + range + "=====文件大小-->" + sourceDataByte.length, true);
                    return response;
                }
            }
            return newFixedLengthResponse("success");
 
        }
        return newFixedLengthResponse("404");
    }
 
    public static Response newFixedLengthResponse(String msg) {
 
        /**
         文本类型:
         text/plain:纯文本
         text/html:HTML 文档
         text/css:CSS 样式表
         text/javascript:JavaScript 脚本
         应用程序类型:
         application/json:JSON 数据
         application/xml:XML 数据
         application/pdf:PDF 文档
         application/octet-stream:二进制数据流
         application/x-www-form-urlencoded:URL 编码的表单数据
         application/zip:ZIP 压缩文件
         application/x-gzip:GZIP 压缩文件
         图片类型:
         image/jpeg:JPEG 图像
         image/png:PNG 图像
         image/gif:GIF 图像
         image/svg+xml:SVG 图像
         音频/视频类型:
         audio/mpeg:MP3 音频
         video/mp4:MP4 视频
         video/mpeg:MPEG 视频
         */
        return newFixedLengthResponse(Response.Status.OK, "application/octet-stream", msg);
    }
 
    public static Response newFixedLengthResponse(byte[] by) {
 
        /**
         文本类型:
         text/plain:纯文本
         text/html:HTML 文档
         text/css:CSS 样式表
         text/javascript:JavaScript 脚本
         应用程序类型:
         application/json:JSON 数据
         application/xml:XML 数据
         application/pdf:PDF 文档
         application/octet-stream:二进制数据流
         application/x-www-form-urlencoded:URL 编码的表单数据
         application/zip:ZIP 压缩文件
         application/x-gzip:GZIP 压缩文件
         图片类型:
         image/jpeg:JPEG 图像
         image/png:PNG 图像
         image/gif:GIF 图像
         image/svg+xml:SVG 图像
         音频/视频类型:
         audio/mpeg:MP3 音频
         video/mp4:MP4 视频
         video/mpeg:MPEG 视频
         */
        return newFixedLengthResponse(NanoHTTPD.Response.Status.OK, "application/octet-stream", new ByteArrayInputStream(by), by.length);
    }
 
}