如何从Nanohttpd提供外部css,jpg和gif文件(Nanohttpd在普通PC上运行而不是在Android上运行)? [英] How do I serve external css, jpg and gif files from Nanohttpd (Nanohttpd run on a normal pc not on Android)?

查看:663
本文介绍了如何从Nanohttpd提供外部css,jpg和gif文件(Nanohttpd在普通PC上运行而不是在Android上运行)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In index.html, External css is used and paths to image src are used to request css images from a folder. However the images are not loaded and css style is not applied to the page.

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和路径to image src用于从文件夹请求图像但是。但是没有加载图像,并且css样式没有应用于页面。

In index.html, External css is used and paths to image src are used to request images from a folder but. However the images are not loaded and css style is not applied to the page.

推荐答案

一旦发回HTML文件,浏览器将运行并对其他资源(图像,JS文件,CSS等)进行后续请求。您需要做的是查看uri参数,这将告诉您需要将哪个文件发送回客户。而不是硬编码index.html,你需要根据所请求的文件名建立文件名。

Once you send back the HTML file, the browser will run though and make subsequent requests for the other resources - images, JS files, CSS, etc. What you will need to do is look at the "uri" parameter and that will tell you which file you need to send back to the client. Instead of hard-coding "index.html" you will need to base the filename off what is being requested.

这篇关于如何从Nanohttpd提供外部css,jpg和gif文件(Nanohttpd在普通PC上运行而不是在Android上运行)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆