部分转载:https://blog.csdn.net/u013738666/article/details/104776840
- 导入依赖
implementation'org.nanohttpd:nanohttpd:2.2.0'
2.创建HttpServer继承NanoHTTPD,收到请求会在serve方法获取到参数信息
package com.swz.test;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import fi.iki.elonen.NanoHTTPD;
public class HttpService extends NanoHTTPD {
public static final String TAG = HttpService.class.getSimpleName();
public HttpService(int port) {
super(port);
}
public HttpService(String hostname, int port) {
super(hostname, port);
}
//重写Serve方法,每次请求时会调用该方法
@Override
public Response serve(IHTTPSession session) {
//通过session获取请求的方式和类型
Method method = session.getMethod();
// 判断post请求并且是上传文件
//将上传数据解析到files集合并且存在NanoHTTPD缓存区
Map files = new HashMap<>();
if (Method.POST.equals(method) || Method.PUT.equals(method)) {
try {
session.parseBody(files);
} catch (IOException ioe) {
return getResponse("Internal Error IO Exception: " + ioe.getMessage());
} catch (ResponseException re) {
return newFixedLengthResponse(re.getStatus(), MIME_PLAINTEXT, re.getMessage());
}
}
//after the body parsed, by default nanoHTTPD will save the file
// to cache and put it into params
//2.将解析出来的文件根据需要保存在本地(或者上传服务器)
Map params = session.getParms();
for (Map.Entry entry : params.entrySet()) {
final String paramsKey = entry.getKey();
//"file"是上传文件参数的key值
if (paramsKey.contains("file")) {
final String tmpFilePath = files.get(paramsKey);
//可以直接拿上传的文件名保存,也可以解析一下然后自己命名保存
final String fileName = entry.getValue();
final File tmpFile = new File(tmpFilePath);
//targetFile是你要保存的file,这里是保存在SD卡的根目录(需要获取文件读写权限)
final File targetFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), fileName);
Log.d("copy file now, source file path<>target file path", tmpFile.getAbsoluteFile()+"<>"+targetFile.getAbsoluteFile());
//a copy file methoed just what you like
copyFile(tmpFile, targetFile);
//maybe you should put the follow code out
return getResponse("Success");
}
}
return response404(session, null);
}
//页面不存在,或者文件不存在时
public Response response404(IHTTPSession session, String url) {
StringBuilder builder = new StringBuilder();
builder.append("body>");
builder.append("404 Not Found" + url + " !");
builder.append("