部分轉(zhuǎn)載:https://blog.csdn.net/u013738666/article/details/104776840
- 導(dǎo)入依賴
implementation'org.nanohttpd:nanohttpd:2.2.0'
2.創(chuàng)建HttpServer繼承NanoHTTPD,收到請求會在serve方法獲取到參數(shù)信息
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方法饼煞,每次請求時會調(diào)用該方法
@Override
public Response serve(IHTTPSession session) {
//通過session獲取請求的方式和類型
Method method = session.getMethod();
// 判斷post請求并且是上傳文件
//將上傳數(shù)據(jù)解析到files集合并且存在NanoHTTPD緩存區(qū)
Map<String, String> 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.將解析出來的文件根據(jù)需要保存在本地(或者上傳服務(wù)器)
Map<String, String> params = session.getParms();
for (Map.Entry<String, String> entry : params.entrySet()) {
final String paramsKey = entry.getKey();
//"file"是上傳文件參數(shù)的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卡的根目錄(需要獲取文件讀寫權(quán)限)
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("<!DOCTYPE html><html>body>");
builder.append("404 Not Found" + url + " !");
builder.append("</body></html>\n");
return NanoHTTPD.newFixedLengthResponse(builder.toString());
}
//成功請求
public Response getResponse(String success) {
StringBuilder builder = new StringBuilder();
builder.append("<!DOCTYPE html><html>body>");
builder.append(success+ " !");
builder.append("</body></html>\n");
return NanoHTTPD.newFixedLengthResponse(builder.toString());
}
public void copyFile(File file, File targetfile) {
FileInputStream fis = null;
FileOutputStream fos = null;
if (!file.exists()) {
System.err.println("File not exists!");
return;
}
try {
fis = new FileInputStream(file);
fos = new FileOutputStream(targetfile);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
fos.flush();
}
} catch (FileNotFoundException ex) {
Logger.getLogger(HttpService.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(HttpService.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException ex) {
Logger.getLogger(HttpService.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
3.開啟服務(wù)
public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
//保存文件需要獲取讀寫權(quán)限
requestPermissions();
initHttpService();
}
private void initHttpService() {
//端口號可以自定義
HttpService http = new HttpService(9988);
try {
http.start();
Toast.makeText(this, "服務(wù)啟動完成", Toast.LENGTH_SHORT).show();
// 啟動完成后根據(jù)IP地址就可以訪問到數(shù)據(jù)了
String localIpAddress = NetWorkUtils.getLocalIpAddress(MainActivity.this);
Log.d("localIpAddress:", "服務(wù)啟動完成");
Log.d("localIpAddress:", localIpAddress);
} catch (IOException e) {
e.printStackTrace();
//System.out.println("服務(wù)啟動錯誤");
Toast.makeText(this, "服務(wù)啟動錯誤", Toast.LENGTH_SHORT).show();
}
}
private void requestPermissions() {
try {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE
}, 0x0010);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 獲取當(dāng)前ip地址
*
* @param context
* @return
*/
public String getLocalIpAddress(Context context) {
try {
WifiManager wifiManager = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int i = wifiInfo.getIpAddress();
return int2ip(i);
} catch (Exception ex) {
return " 獲取IP出錯施禾!請保證是WIFI,或者請重新打開網(wǎng)絡(luò)!\n" + ex.getMessage();
}
// return null;
}
/**
* 將ip的整數(shù)形式轉(zhuǎn)換成ip形式
*
* @param ipInt
* @return
*/
public String int2ip(int ipInt) {
StringBuilder sb = new StringBuilder();
sb.append(ipInt & 0xFF).append(".");
sb.append((ipInt >> 8) & 0xFF).append(".");
sb.append((ipInt >> 16) & 0xFF).append(".");
sb.append((ipInt >> 24) & 0xFF);
return sb.toString();
}
}
4.在清單文件添加網(wǎng)絡(luò)和文件讀寫權(quán)限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
下面是如何返回文件
//成功請求
public Response getResponseFile(String fileName) {
String filePath = Environment.getExternalStorageDirectory().getAbsolutePath()+ "/msc/" + fileName;
try {
InputStream fileInputStream = new FileInputStream(filePath);
//mimeType 是下載文件的類型脚线,可以百度找一下你返回文件的類型寫法
// '.a' : 'application/octet-stream',
// '.avi' : 'video/x-msvideo',
// '.bat' : 'text/plain',
// '.wav' : 'audio/x-wav',
// '.bin' : 'application/octet-stream',
// '.bmp' : 'image/x-ms-bmp',
// '.c' : 'text/plain',
return NanoHTTPD.newFixedLengthResponse(Response.Status.OK,"audio/x-wav",fileInputStream,fileInputStream.available());
} catch (FileNotFoundException e) {
e.printStackTrace();
return response404();
} catch (IOException e) {
e.printStackTrace();
return response404();
}
}
NetWorkUtils代碼
public class NetWorkUtils {
/**
* 將ip的整數(shù)形式轉(zhuǎn)換成ip形式
*
* @param ipInt
* @return
*/
public static String int2ip(int ipInt) {
StringBuilder sb = new StringBuilder();
sb.append(ipInt & 0xFF).append(".");
sb.append((ipInt >> 8) & 0xFF).append(".");
sb.append((ipInt >> 16) & 0xFF).append(".");
sb.append((ipInt >> 24) & 0xFF);
return sb.toString();
}
/**
* 獲取當(dāng)前ip地址
*
* @param context
* @return
*/
public static String getLocalIpAddress(Context context) {
try {
WifiManager wifiManager = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int i = wifiInfo.getIpAddress();
return int2ip(i);
} catch (Exception ex) {
return " 獲取IP出錯!請保證是WIFI,或者請重新打開網(wǎng)絡(luò)!\n" + ex.getMessage();
}
// return null;
}
}