使用NanoHttpd在Android项目中搭建服务器

NanoHTTPD是一个免费、轻量级的(只有一个Java文件) HTTP服务器,可以很好地嵌入到Java程序中。支持 GET, POST, PUT, HEAD 和 DELETE 请求,支持文件上传,占用内存很小。

github地址:https://github.com/NanoHttpd/nanohttpd

下载完demo项目后,解压,找到路径,我的是放在F盘下:

F:\nanohttpd-master\core\src\main\java\org\nanohttpd

把整个nanohttpd文件夹复制到项目下即可使用了。

项目中的截图如下:

如果比较懒不想去github下载的话,可以直接在build.gradle中添加依赖(我之前是不知道这个依赖,所以用的是下载的文件):

implementation'org.nanohttpd:nanohttpd:2.2.0'

 具体使用:

首先先写一个类FileServer继承nanohttpd:

package caro.automation.server;

import org.nanohttpd.protocols.http.IHTTPSession;
import org.nanohttpd.protocols.http.NanoHTTPD;
import org.nanohttpd.protocols.http.response.Response;
import org.nanohttpd.protocols.http.response.Status;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

/**
 * Created by XDA on 2019/4/2.
 */
public class FileServer extends NanoHTTPD {
//    public static final int DEFAULT_SERVER_PORT= com.example.zjt.nanohttpexample.Status.MY_PORT;//为8080
    public static final int DEFAULT_SERVER_PORT= 8080;//为8080
    public static final String TAG = FileServer.class.getSimpleName();
    //根目录
    private static  final String REQUEST_ROOT = "/";
    private List<SharedFile> fileList;//用于分享的文件列表

    public FileServer(List<SharedFile> fileList){
        super(DEFAULT_SERVER_PORT);
        this.fileList = fileList;
    }
    //当接受到连接时会调用此方法
    public Response serve(IHTTPSession session){
        if(REQUEST_ROOT.equals(session.getUri())||session.getUri().equals("")){
            return responseRootPage(session);
        }
        return responseFile(session);
    }
    //对于请求根目录的,返回分享的文件列表
    public Response responseRootPage(IHTTPSession session){
        StringBuilder builder = new StringBuilder();
        builder.append("<!DOCTYPER html><html><body>");
        builder.append("<ol>");
        for(int i = 0 , len = fileList.size(); i < len ; i++){
            File file = new File(fileList.get(i).getPath());
            if(file.exists()){
                //文件及下载文件的链接,定义了一个文件类,这里使用getPath方法获得路径,使用getName方法获得文件名
                builder.append("<li> <a href=\""+file.getPath()+"\">"+file.getName()+"</a></li>");
            }
        }
        builder.append("<li>分享文件数量:  "+fileList.size()+"</li>");
        builder.append("</ol>");
        builder.append("</body></html>\n");
        //回送应答
        return Response.newFixedLengthResponse(String.valueOf(builder));
    }
    //对于请求文件的,返回下载的文件
    public Response responseFile(IHTTPSession session){
        try {
            //uri:用于标示文件资源的字符串,这里即是文件路径
            String uri = session.getUri();
            //文件输入流
            FileInputStream fis = new FileInputStream(uri);
            // 返回OK,同时传送文件,为了安全这里应该再加一个处理,即判断这个文件是否是我们所分享的文件,避免客户端访问了其他个人文件
            return Response.newFixedLengthResponse(Status.OK,"application/octet-stream",fis,fis.available());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response404(session,null);
    }
    //页面不存在,或者文件不存在时
    public Response response404(IHTTPSession session,String url) {
        StringBuilder builder = new StringBuilder();
        builder.append("<!DOCTYPE html><html>body>");
        builder.append("Sorry,Can't Found" + url + " !");
        builder.append("</body></html>\n");
        return Response.newFixedLengthResponse(builder.toString());
    }
}

然后创建一个服务类HttpServer来开启FileServer:

package caro.automation.server;

import org.nanohttpd.protocols.http.IHTTPSession;
import org.nanohttpd.protocols.http.NanoHTTPD;
import org.nanohttpd.protocols.http.response.Response;
import org.nanohttpd.protocols.http.response.Status;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import caro.automation.MyApplication;
import caro.automation.modify.DatabaseSelectUpload;

/**
 * Created by XDA on 2019/3/25.
 */
public class HttpServer extends NanoHTTPD {
    private static final String TAG = "Http";
    public HttpServer(int port) {
        super(port);
    }






    @Override
    public Response serve(IHTTPSession session) {


            try {
                for (int i = 0; i < DatabaseSelectUpload.name_.size(); i++) {  //for 循环文件名 小于name的个数
                session.parseBody(new HashMap<String, String>());
                final String choose = DatabaseSelectUpload.name_.get(i);//获取循环到的文件名
                String strDBPath = MyApplication.GetApp().getExternalFilesDir(null) + "/TIS-Smarthome/" + choose + "/" + (choose + ".db3");//数据库地址

                    FileInputStream fis = new FileInputStream(strDBPath);

                    return Response.newFixedLengthResponse(Status.OK, "application/octet-stream", fis, fis.available());
                }

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ResponseException e) {
                e.printStackTrace();
            }

        return response404(session, null);
    }

    //页面不存在,或者文件不存在时
    public Response response404(IHTTPSession session,String url) {
               StringBuilder builder = new StringBuilder();
        builder.append("<!DOCTYPE html><html>body>");
        builder.append("Sorry,Can't Found" + url + " !");
        builder.append("</body></html>\n");
        return Response.newFixedLengthResponse(builder.toString());
    }



}

ps: 

"application/octet-stream"

这个参数的意思是以流的形式下载文件,这样可以实现任意格式的文件下载。

 

然后在需要开启服务器的地方,例如在Activity的onCreate方法中开启:

startService(new Intent(getApplicationContext(),MyServer.class));//开启NanoHttpD 8080端口

记得在onDestroy方法中关闭服务器:

stopService(new Intent(getApplicationContext(),MyServer.class)); //关闭 NanoHTTPD   8080

我的是192.168.1.168:8080 打开后可以看到:

这里显示的就是页面为空的时候的显示。response404()方法里面写好的显示内容。

 

这样就是成功开启了服务器了。然后就可以根据这个url来上传下载文件。

我这边是使用的OKgo来上传下载文件的。下一篇会介绍一下我自己写的辣鸡代码。

简单使用Okgo上传下载文件,有兴趣可以瞄一下。

  • 2
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 使用Android Studionanohttpd库创建HTTP服务器,并使用WebView打开HTML页面的步骤如下: 1. 首先,在build.gradle文件的dependencies块添加依赖项: ``` implementation 'org.nanohttpd:nanohttpd-webserver:2.3.1' ``` 2. 在需要创建HTTP服务器的Activity,创建一个继承自NanoHTTPD的子类。例如: ```java public class MyServer extends NanoHTTPD { public MyServer() { super(8080); // 设置服务器端口为8080 } @Override public Response serve(IHTTPSession session) { String uri = session.getUri(); // 获取请求的URI // 判断请求的URI是否为根目录,如果是,则返回HTML页面,否则返回404错误 if (uri.equals("/")) { try { InputStream inputStream = getAssets().open("index.html"); // 打开assets文件夹的index.html文件 BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line); } reader.close(); inputStream.close(); String html = builder.toString(); return newFixedLengthResponse(Response.Status.OK, "text/html", html); // 返回HTML页面 } catch (IOException e) { e.printStackTrace(); } } return newFixedLengthResponse(Response.Status.NOT_FOUND, "text/plain", "404 Not Found"); // 返回404错误 } } ``` 3. 在Activity启动HTTP服务器,并使用WebView打开页面: ```java WebView webView = findViewById(R.id.webView); webView.getSettings().setJavaScriptEnabled(true); // 允许WebView执行JavaScript代码 MyServer server = new MyServer(); try { server.start(); // 启动HTTP服务器 } catch (IOException e) { e.printStackTrace(); } webView.loadUrl("http://localhost:8080/"); // 使用WebView打开服务器的根目录页面 ``` 以上就是使用NanoHTTPD创建HTTP服务器使用WebView打开HTML页面的过程。在实际开发,可以根据需要进行相应的修改和扩展。 ### 回答2: 要使用Android Studio创建一个HTTP服务器并打开HTML页面,可以使用NanoHTTPD库来实现。 首先,需要在项目的`build.gradle`文件添加NanoHTTPD的依赖项。在`dependencies`部分添加以下代码: ``` implementation 'org.nanohttpd:nanohttpd:2.3.1' ``` 接下来,在你的Activity或Fragment创建一个NanoHTTPD的子类,例如`MyServer`。这个子类需要实现`NanoHTTPD.IHTTPD`接口,并重写`serve()`方法来响应HTTP请求。在这个方法,你可以通过判断请求URI来确定要返回给客户端的内容。 具体代码如下: ```java import android.content.Context; import android.webkit.WebView; import android.widget.Toast; import org.nanohttpd.protocols.http.IHTTPSession; import org.nanohttpd.protocols.http.NanoHTTPD; import org.nanohttpd.protocols.http.response.Response; import org.nanohttpd.protocols.http.response.Status; import java.io.IOException; public class MyServer extends NanoHTTPD { private Context context; public MyServer(Context context) { super(8080); this.context = context; } @Override public Response serve(IHTTPSession session) { String uri = session.getUri(); if (uri.equals("/index.html")) { String html = "<html><body><h1>Hello, World!</h1></body></html>"; return newFixedLengthResponse(Response.Status.OK, "text/html", html); } else { return newFixedLengthResponse(Response.Status.NOT_FOUND, "text/plain", "404 Not Found"); } } } ``` 然后,在你的Activity或Fragment,可以通过创建一个WebView来加载HTML页面,并启动NanoHTTPD服务器。具体代码如下: ```java import android.os.Bundle; import android.webkit.WebView; import android.webkit.WebViewClient; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private WebView webView; private MyServer server; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); webView = findViewById(R.id.webView); webView.getSettings().setJavaScriptEnabled(true); webView.setWebViewClient(new WebViewClient()); server = new MyServer(this); try { server.start(); Toast.makeText(this, "Server started", Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); } webView.loadUrl("http://localhost:8080/index.html"); } @Override protected void onDestroy() { super.onDestroy(); if (server != null) { server.stop(); } } } ``` 在XML布局文件添加一个WebView用于显示HTML页面。 这样,当你运行这个应用时,会在Android设备上启动一个HTTP服务器,并使用WebView加载服务器上的HTML页面。 ### 回答3: 使用Android Studio创建HTTP服务器并在WebView打开HTML页面需要以下步骤: 1. 首先,将nanohttpd库导入到Android Studio项目。可以通过在项目的build.gradle文件添加以下行来实现: ```groovy dependencies { implementation 'org.nanohttpd:nanohttpd:2.3.1' } ``` 2. 创建一个新的Java类,继承自`NanoHTTPD`类,用于实现HTTP服务器。在这个类,需要重写NanoHTTPD的`serve()`方法,来处理HTTP请求和响应。通过使用`InputStream`读取HTML文件的内容,并将其响应给请求的客户端。 ```java public class MyHTTPServer extends NanoHTTPD { // 构造方法 public MyHTTPServer() { super(8080); } @Override public Response serve(IHTTPSession session) { String uri = session.getUri(); if (uri.equals("/")) { uri = "/index.html"; } try { InputStream inputStream = getApplicationContext().getAssets().open(uri.substring(1)); String mimeType = "text/html"; return newChunkedResponse(Response.Status.OK, mimeType, inputStream); } catch (IOException e) { e.printStackTrace(); return newFixedLengthResponse(Response.Status.NOT_FOUND, "text/plain", "File not found"); } } } ``` 3. 在AndroidManifest.xml文件添加以下权限: ```xml <uses-permission android:name="android.permission.INTERNET" /> ``` 4. 在Activity的`onCreate()`方法启动HTTP服务器并加载WebView: ```java public class MainActivity extends AppCompatActivity { private WebView webView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 启动HTTP服务器 MyHTTPServer server = new MyHTTPServer(); try { server.start(); } catch (IOException e) { e.printStackTrace(); } webView = findViewById(R.id.webView); // 允许WebView执行JavaScript代码 webView.getSettings().setJavaScriptEnabled(true); // 加载HTTP服务器的地址 webView.loadUrl("http://localhost:8080"); } } ``` 以上是在Android Studio使用NanoHTTPD库创建HTTP服务器并在WebView打开HTML页面的步骤。可以根据需要对服务器和WebView进行进一步的自定义和配置。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值