Android作为服务端(NanoHTTPD,实现上传,返回文件功能)

部分转载:https://blog.csdn.net/u013738666/article/details/104776840

  1. 导入依赖
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("\n");
        return NanoHTTPD.newFixedLengthResponse(builder.toString());
    }

    //成功请求
    public Response getResponse(String success) {
        StringBuilder builder = new StringBuilder();
        builder.append("body>");
        builder.append(success+ " !");
        builder.append("\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.开启服务

public class MainActivity extends Activity {

          public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              requestWindowFeature(Window.FEATURE_NO_TITLE);
              setContentView(R.layout.main);
              //保存文件需要获取读写权限
              requestPermissions();
              initHttpService();
          }

            private void initHttpService() {
                  //端口号可以自定义
                 HttpService http = new HttpService(9988);
                 try {
                    http.start();
                    Toast.makeText(this, "服务启动完成", Toast.LENGTH_SHORT).show();
                    //  启动完成后根据IP地址就可以访问到数据了
                    String localIpAddress = NetWorkUtils.getLocalIpAddress(MainActivity.this);
                    Log.d("localIpAddress:", "服务启动完成");
                    Log.d("localIpAddress:", localIpAddress);
                } catch (IOException e) {
                    e.printStackTrace();
                    //System.out.println("服务启动错误");
                    Toast.makeText(this, "服务启动错误", 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();
                }
            }

    /**
     * 获取当前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,或者请重新打开网络!\n" + ex.getMessage();
        }
        // return null;
    }

    /**
     * 将ip的整数形式转换成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.在清单文件添加网络和文件读写权限




下面是如何返回文件

//成功请求
    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的整数形式转换成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();
    }

    /**
     * 获取当前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,或者请重新打开网络!\n" + ex.getMessage();
        }
        // return null;
    }
}

你可能感兴趣的:(Android作为服务端(NanoHTTPD,实现上传,返回文件功能))