编程语言
首页 > 编程语言> > java – 如何从Nanohttpd提供外部css,jpg和gif文件(Nanohttpd在普通PC上运行而不是在Android上运行)?

java – 如何从Nanohttpd提供外部css,jpg和gif文件(Nanohttpd在普通PC上运行而不是在Android上运行)?

作者:互联网

在index.html中,使用外部css,图像src的路径用于从文件夹请求css图像.但是,未加载图像,并且css样式未应用于页面.

import java.io.*;
import java.util.*;

/**
 * An example of subclassing NanoHTTPD to make a custom HTTP server.
 */
public class HelloServer extends NanoHTTPD
{
    public HelloServer() throws IOException
    {
        super(8080, new File("."));
    }

    public Response serve(String uri, String method, Properties header, Properties parms, Properties files) {

        BufferedReader br = null;
        String msg="";

        try {

            String sCurrentLine;

            br = new BufferedReader(new FileReader("index.html"));

            while ((sCurrentLine = br.readLine()) != null) {
                //System.out.println(sCurrentLine);
                msg = msg + sCurrentLine;
                System.out.println(sCurrentLine);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null)br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return new NanoHTTPD.Response( HTTP_OK, MIME_HTML, msg );
    }


    public static void main( String[] args )
    {
        try
        {
            new HelloServer();
        }
        catch( IOException ioe )
        {
            System.err.println( "Couldn't start server:\n" + ioe );
            System.exit( -1 );
        }
        System.out.println( "Listening on port 8080. Hit Enter to stop.\n" );
        try { System.in.read(); } catch( Throwable t ) {};
    }
}

在index.html中,使用外部css,图像src的路径用于从文件夹请求图像.但是,未加载图像,并且css样式未应用于页面.

解决方法:

一旦你发回HTML文件,浏览器就会运行并对其他资源做出后续请求 – 图像,JS文件,CSS等.你需要做的是查看“uri”参数,它会告诉你您需要将哪个文件发送回客户端.您不需要对“index.html”进行硬编码,而是需要根据所请求的内容来设置文件名.

标签:java,nanohttpd
来源: https://codeday.me/bug/20191008/1875402.html