问题
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 ) {};
}
}
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.
回答1:
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.
来源:https://stackoverflow.com/questions/18030214/how-do-i-serve-external-css-jpg-and-gif-files-from-nanohttpd-nanohttpd-run-on