GithubHelp home page GithubHelp logo

nanohttpd / nanohttpd Goto Github PK

View Code? Open in Web Editor NEW
6.9K 355.0 1.7K 1.34 MB

Tiny, easily embeddable HTTP server in Java.

Home Page: http://nanohttpd.org

License: BSD 3-Clause "New" or "Revised" License

Java 98.42% HTML 1.58%

nanohttpd's Introduction

NanoHTTPD – a tiny web server in Java

NanoHTTPD is a light-weight HTTP server designed for embedding in other applications, released under a Modified BSD licence.

It is being developed at Github and uses Apache Maven for builds & unit testing:

  • Build status: Build Status
  • Coverage Status: Coverage Status
  • Current central released version: Maven Central

Quickstart

We'll create a custom HTTP server project using Maven for build/dep system. This tutorial assumes you are using a Unix variant and a shell. First, install Maven and Java SDK if not already installed. Then run:

mvn compile
mvn exec:java -pl webserver -Dexec.mainClass="org.nanohttpd.webserver.SimpleWebServer"

You should now have a HTTP file server running on http://localhost:8080/.

Custom web app

Let's raise the bar and build a custom web application next:

mvn archetype:generate -DgroupId=com.example -DartifactId=myHellopApp -DinteractiveMode=false
cd myHellopApp

Edit pom.xml, and add this between <dependencies>:

<dependency>
	<groupId>org.nanohttpd</groupId> <!-- <groupId>com.nanohttpd</groupId> for 2.1.0 and earlier -->
	<artifactId>nanohttpd</artifactId>
	<version>2.2.0</version>
</dependency>

Edit src/main/java/com/example/App.java and replace it with:

    package com.example;
    
    import java.io.IOException;
    import java.util.Map;
    
    import fi.iki.elonen.NanoHTTPD;
    // NOTE: If you're using NanoHTTPD >= 3.0.0 the namespace is different,
    //       instead of the above import use the following:
	// import org.nanohttpd.NanoHTTPD;
    
    public class App extends NanoHTTPD {
    
        public App() throws IOException {
            super(8080);
            start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
            System.out.println("\nRunning! Point your browsers to http://localhost:8080/ \n");
        }
    
        public static void main(String[] args) {
            try {
                new App();
            } catch (IOException ioe) {
                System.err.println("Couldn't start server:\n" + ioe);
            }
        }
    
        @Override
        public Response serve(IHTTPSession session) {
            String msg = "<html><body><h1>Hello server</h1>\n";
            Map<String, String> parms = session.getParms();
            if (parms.get("username") == null) {
                msg += "<form action='?' method='get'>\n  <p>Your name: <input type='text' name='username'></p>\n" + "</form>\n";
            } else {
                msg += "<p>Hello, " + parms.get("username") + "!</p>";
            }
            return newFixedLengthResponse(msg + "</body></html>\n");
        }
    }

Compile and run the server:

mvn compile
mvn exec:java -Dexec.mainClass="com.example.App"

If it started ok, point your browser at http://localhost:8080/ and enjoy a web server that asks your name and replies with a greeting.

Nanolets

Nanolets are like servlets only that they have a extremely low profile. They offer an easy to use system for a more complex server application. This text has to be extended with an example, so for now take a look at the unit tests for the usage. https://github.com/NanoHttpd/nanohttpd/blob/master/nanolets/src/test/java/org/nanohttpd/junit/router/AppNanolets.java

Status

We are currently in the process of stabilizing NanoHTTPD from the many pull requests and feature requests that were integrated over the last few months. The next release will come soon, and there will not be any more "intended" major changes before the next release. If you want to use the bleeding edge version, you can clone it from Github, or get it from sonatype.org (see "Maven dependencies / Living on the edge" below).

Project structure

NanoHTTPD project currently consist of four parts:

  • /core – Fully functional HTTP(s) server consisting of one (1) Java file, ready to be customized/inherited for your own project.

  • /samples – Simple examples on how to customize NanoHTTPD. See HelloServer.java for a killer app that greets you enthusiastically!

  • /websocket – Websocket implementation, also in a single Java file. Depends on core.

  • /webserver – Standalone file server. Run & enjoy. A popular use seems to be serving files out off an Android device.

  • /nanolets – Standalone nano app server, giving a servlet like system to the implementor.

  • /fileupload – integration of the apache common file upload library.

Features

Core

  • Only one Java file, providing HTTP 1.1 support.
  • No fixed config files, logging, authorization etc. (Implement by yourself if you need them. Errors are passed to java.util.logging, though.)
  • Support for HTTPS (SSL).
  • Basic support for cookies.
  • Supports parameter parsing of GET and POST methods.
  • Some built-in support for HEAD, POST and DELETE requests. You can easily implement/customize any HTTP method, though.
  • Supports file upload. Uses memory for small uploads, temp files for large ones.
  • Never caches anything.
  • Does not limit bandwidth, request time or simultaneous connections by default.
  • All header names are converted to lower case so they don't vary between browsers/clients.
  • Persistent connections (Connection "keep-alive") support allowing multiple requests to be served over a single socket connection.

Websocket

  • Tested on Firefox, Chrome and IE.

Webserver

  • Default code serves files and shows (prints on console) all HTTP parameters and headers.
  • Supports both dynamic content and file serving.
  • File server supports directory listing, index.html and index.htm.
  • File server supports partial content (streaming & continue download).
  • File server supports ETags.
  • File server does the 301 redirection trick for directories without /.
  • File server serves also very long files without memory overhead.
  • Contains a built-in list of most common MIME types.
  • Runtime extension support (extensions that serve particular MIME types) - example extension that serves Markdown formatted files. Simply including an extension JAR in the webserver classpath is enough for the extension to be loaded.
  • Simple CORS support via --cors parameter
    • by default serves Access-Control-Allow-Headers: origin,accept,content-type
    • possibility to set Access-Control-Allow-Headers by setting System property: AccessControlAllowHeader
    • _example: _ -DAccessControlAllowHeader=origin,accept,content-type,Authorization
    • possible values:
      • --cors: activates CORS support, Access-Control-Allow-Origin will be set to *.
      • --cors=some_value: Access-Control-Allow-Origin will be set to some_value.

CORS argument examples

  • --cors=http://appOne.company.com
  • --cors="http://appOne.company.com, http://appTwo.company.com": note the double quotes so that the two URLs are considered part of a single argument.

Maven dependencies

NanoHTTPD is a Maven based project and deployed to central. Most development environments have means to access the central repository. The coordinates to use in Maven are:

<dependencies>
	<dependency>
		<groupId>org.nanohttpd</groupId> <!-- <groupId>com.nanohttpd</groupId> for 2.1.0 and earlier -->
		<artifactId>nanohttpd</artifactId>
		<version>CURRENT_VERSION</version>
	</dependency>
</dependencies>

(Replace CURRENT_VERSION with whatever is reported latest at http://nanohttpd.org/.)

The coordinates for your development environment should correspond to these. When looking for an older version take care because we switched groupId from com.nanohttpd to org.nanohttpd in mid 2015.

Next it depends what you are using NanoHTTPD for, there are three main usages.

Gradle dependencies

In gradle you can use NanoHTTPD the same way because gradle accesses the same central repository:

dependencies {
	runtime(
		[group: 'org.nanohttpd', name: 'nanohttpd', version: 'CURRENT_VERSION'],
	)
}

(Replace CURRENT_VERSION with whatever is reported latest at http://nanohttpd.org/.)

Just replace the name with the artifact id of the module you want to use and gradle will find it for you.

Develop your own specialized HTTP service

For a specialized HTTP (HTTPS) service you can use the module with artifactId nanohttpd.

	<dependency>
		<groupId>org.nanohttpd</groupId> <!-- <groupId>com.nanohttpd</groupId> for 2.1.0 and earlier -->
		<artifactId>nanohttpd</artifactId>
		<version>CURRENT_VERSION</version>
	</dependency>

Here you write your own subclass of org.nanohttpd.NanoHTTPD to configure and to serve the requests.

Develop a websocket based service

For a specialized websocket service you can use the module with artifactId nanohttpd-websocket.

	<dependency>
		<groupId>org.nanohttpd</groupId> <!-- <groupId>com.nanohttpd</groupId> for 2.1.0 and earlier -->
		<artifactId>nanohttpd-websocket</artifactId>
		<version>CURRENT_VERSION</version>
	</dependency>

Here you write your own subclass of org.nanohttpd.NanoWebSocketServer to configure and to serve the websocket requests. A small standard echo example is included as org.nanohttpd.samples.echo.DebugWebSocketServer. You can use it as a starting point to implement your own services.

Develop a custom HTTP file server

For a more classic approach, perhaps to just create a HTTP server serving mostly service files from your disk, you can use the module with artifactId nanohttpd-webserver.

	<dependency>
		<groupId>org.nanohttpd</groupId>
		<artifactId>nanohttpd-webserver</artifactId>
		<version>CURRENT_VERSION</version>
	</dependency>

The included class org.nanohttpd.SimpleWebServer is intended to be used as a starting point for your own implementation but it also can be used as is. Starting the class as is will start a HTTP server on port 8080 and publishing the current directory.

Living on the edge

The latest Github master version can be fetched through sonatype.org:

<dependencies>
	<dependency>
		<artifactId>nanohttpd</artifactId>
		<groupId>org.nanohttpd</groupId>
		<version>XXXXX-SNAPSHOT</version>
	</dependency>
</dependencies>
...
<repositories>
	<repository>
		<id>sonatype-snapshots</id>
		<url>https://oss.sonatype.org/content/repositories/snapshots</url>
		<snapshots>
			<enabled>true</enabled>
		</snapshots>
	</repository>
</repositories>

generating an self signed SSL certificate

Just a hint how to generate a certificate for localhost.

keytool -genkey -keyalg RSA -alias selfsigned -keystore keystore.jks -storepass password -validity 360 -keysize 2048 -ext SAN=DNS:localhost,IP:127.0.0.1  -validity 9999

This will generate a keystore file named 'keystore.jks' with a self signed certificate for a host named localhost with the IP address 127.0.0.1 . Now you can use:

server.makeSecure(NanoHTTPD.makeSSLSocketFactory("/keystore.jks", "password".toCharArray()), null);

Before you start the server to make NanoHTTPD serve HTTPS connections, when you make sure 'keystore.jks' is in your classpath.


Thank you to everyone who has reported bugs and suggested fixes.

nanohttpd's People

Contributors

alaazayed avatar artichikin avatar bjoernakamanf avatar brunoeberhard avatar cpu avatar cypressious avatar dunmatt avatar eighthave avatar elonen avatar josh-larson avatar lordfokas avatar luctrudeau avatar martinmreed avatar mcfoggy avatar philippwiesemann avatar psh avatar rherrmann avatar ritchiegithub avatar rnveach avatar santagaz avatar sgallese avatar sherifmoursi avatar snostorm avatar steventebrinke avatar tagback avatar tatsuyafw avatar twhitbeck avatar vnnv avatar williamdo avatar yankee42 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nanohttpd's Issues

Make artifacts available on Maven Central

Since this is an embeddable server, it would be very handy to make it available on Maven Central (or somewhere - please let me know if it is on another public maven repo which I haven't been able to find)

Other Content-Types in POST

Nano supports multipart/form-data and application/x-www-form-urlencoded with everything else ignored, unparsed. Would be good to actually be able to tap into the raw data for custom Content-Types and be able to process them in NanoHTTPD extensions.

Can provide patch if pull requests are actually accepted and applied.

SSL support.

I have SSL support working for NanoHTTPD. It was only a few lines and supports the 1/n-1 split that the major browsers use. The certificates are handled through keystores. Would you be interested in adding this functionality or would you like to leave it as HTTP only? I have the modified version available in a repo on my account.

nanohttpd can't get parameter when upload files in LieBao browser

i use LieBao browser open the test file \core\src\test\resources\file-upload-test.htm and upload some files to fi.iki.elonen.DebugServer,but debugServer can't print any Parms and Files.there are both empty.
but threre is no this issues when i use other browser like FireFox, IE8,Chrome。
Liebao browse's Official Site is www.liebao.cn

Add a Gradle build

As a developer without Maven installed on my machine, I would like to be able to build and use NanoHttpd. Investigate and write a build for the software that uses Gradle, and whether important properties (version, name, etc) can be held in common property files across both builds.

Collections.EMPTY_MAP maybe better.

public Response serve(IHTTPSession session) {
Map<String, String> files = new HashMap<String, String>();
// Map<String, String> files = Collections.EMPTY_MAP;

and IHTTPSession has an spell error. Map<String, String> getParms();

Response.send does not handle streaming responses correctly?

I'm attempting to use NanoHTTPD for streaming responses by creating a PipedInputStream/PipedOutputStream pair, starting a thread to write to the PipedOutputStream and then constructing the NanoHTTPD.Response using the PipedInputStream. Unfortunately, due to the following code, NanoHTTPD decides there isn't much data to be sent, writes an incorrect Content-Length header, then closes the InputStream:

            int pending = data != null ? data.available() : -1; // This is to support partial sends, see serveFile()
            if (pending > 0) {
                pw.print("Connection: keep-alive\r\n");
                pw.print("Content-Length: "+pending+"\r\n");
            }

The problem is that when 'data' is a PipedInputStream, data.available() is not necessarilyi indicative of the entire length of the stream, as all the data may not yet be available for reading.

I have seen comments to the effect that NanoHTTPD has been improved for streaming, but I don't see how this is possible unless I'm going about it all wrong. I've hacked up my own Response that overrides send() and it's working, but I'm curious what NanoHTTPD maintainers have to say about the issue.

Build Faile on Vanilla Xbuntu 12.04. Maven Issues. Stock Oracle JDK7 + Netbeans Bundle

Hello,

I have a question. Upon testing the source I ran into problems. This Linux box is brand new and is essentially Ubuntu. I am using Oracle JDK 7 bundled with netbeans. No crazy additions.

When I tested the source I ran into this,

Failed to execute goal on project nanohttpd-samples: Could not resolve dependencies for project fi.iki.elonen:nanohttpd-samples:jar:2.0.2: The following artifacts could not be resolved: fi.iki.elonen:nanohttpd:jar:2.0.2, fi.iki.elonen:nanohttpd-webserver:jar:2.0.2: Failure to find fi.iki.elonen:nanohttpd:jar:2.0.2 in http://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced -> [Help 1]

Which I think it has to do with Maven. The problem is I don't know much about Maven.

I looked here as well, no help.

[Help 1] http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException

What on earth can I do?

Multi-instance Nano

There are several static variables that impede the ability to run Nano on several ports in embedded mode. RUNNING, currentIP and currentPort are three of them, there may be more. Will submit a patch if you intend on pulling. You acknowledged one of my earlier pull requests but never actually merged, so not sure whether you're even looking to merge contributions in the first place, so letting you know for now.

Simplify request handling code

The change to write the incoming request to file, and map that into memory (using ByteBuffer) introduces a new opportunity - continue the refactoring to remove the BufferedReader that we attach back on that file, and switch to reading from the `ByteBuffer`` directly. Currently the code looks a little odd as it drops between both schemes.

Note: The profiling the application it was obvious that there's a speedup to be had as multipart boundaries are traversed. Instead of reading line by line and throwing the data away, try skipping a number of bytes in a single seek() call!

Some enhancement propositions

I have some enhancements to propose, in order to provide the user with more power and flexibility.

I was going to propose sending the HTTPSession object instead of all those args in NanoHTTPD.serve(), but I see you already did that.

Since I'm using NanoHTTPD to make the server side of a browser game, I need the serve() method to receive the client IP address. This is something I implemented myself easily, but other users may find useful as well.

Finally, adding Cookie-handling methods to the HTTP session object would be really useful.

Roll version number on _master_

The 1.x (Java 1.1) development continues happily on a branch. As it stands the version on master is a generic "1.0.0" and ought to be updated to (say) "2.0.0" to reflect steps made.

decodePercent() in NanoHTTPD is not handling non-english filenames correctly

decodePercent() is breaking up the multi-byte UTF8 characters into individual bytes. Hence, it cannot serve any files with non-english names.

Reverting it back to URLDecoder fix this problem:

protected String decodePercent(String str) {
String s = null;
try { s = URLDecoder.decode(str, "UTF8"); } catch (UnsupportedEncodingException ignored) { }
return s;
}

SERVER INTERNAL ERROR: 500

I made test with NanoHTTPD, in an Android Application and a Raspberry PI.

And in each case, after receive my 200 response, after timer SOCKET_READ_TIMEOUT (5000ms), i receive an 500 Error from server...

trace

send() Doesn't support Unicode

Suggest making changes:
FROM:
PrintWriter pw = new PrintWriter(outputStream);
TO:
Writer pw = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));

NANOHTTPD-... temp files is not deleted

Hi, I have a server class that extends Nanohttp class. My problem is temp files couldn't be deleted. I tried orginal example files and same issue exist on these examples. temp file Clear method is called, "Cleaning up: ..." writes on console and file paths are ture and files are exist but not deleted. When I try to delete files normally on windows with keyboard delete key, and windows give me an error "this action can not be completed beacuse the file is open in Java platform binary" (while i try delete files, server is still running). If i stop server, i can delete files manually. Is there any possibility to be forgotten something (any stream or file handler) open in NanoHttpd class?

Thanks,

In the HTTPSession.serve access socket, in order to get the remote client IP

So that we can

protected Response serve(HTTPSession session) {
    // remote-addr and http-client-ip
    InetAddress remoteAddr = ((InetSocketAddress) session.getSocket().getRemoteSocketAddress()).getAddress();
    String remoteIp = remoteAddr.isLoopbackAddress() || remoteAddr.isAnyLocalAddress() ? "127.0.0.1" : remoteAddr.getHostAddress().toString();
    session.getHeaders().put("remote-addr", remoteIp);
    session.getHeaders().put("http-client-ip", remoteIp);
    return super.serve(session);
}

Encodage problems

Hello,

When I do something like this on serve(...) :

return new Response("Désolé, cette adresse email est déjà utilisée.");

I have this on the page : Désolé, ce nom est déjà utilisé.

Could you fix this ?

Thanks !

decodePercent does not handle UTF-8 Properly

UTF-8 Percent Encoded entities are often multibyte. However for example a multi-byte UTF-8 Entity shouldn't be added to a StringBuffer one byte at a time. Rather the multi-byte entity should be fully decoded into a single "multi-byte character" and be added to a String buffer as a single unit.

I'm not sure why NanoHTTPD does not use the URLDecoder class, but if it did you could do something like:

    private String decodePercent( String str ) throws InterruptedException
    {
        try {
            // Using URLDecoder since it understands UTF-8
            return URLDecoder.decode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            sendError( HTTP_BADREQUEST, "BAD REQUEST: Bad percent-encoding." );
            e.printStackTrace();
            return null;
        }
    }

If trying to avoid the URLDecoder class, perhaps using CharsetDecoder would help. However in my personal use case, URLDecoder is perfectly acceptable.

Hope that helps.

Code error

The following line does not seem OK to me:

if (boundary.startsWith(""") && boundary.startsWith("""))

I hope you trust .startsWith() function and so you don't call it two times intentionally... :-)

What are nanohttpd's thoughts on the following features

I am building a HTTP server to run inside of a web browser as part of the https://peerly.codeplex.com/ peer to peer web project. I'm using NanoHTTPD because it runs both on the desktop and in Android. But there are a couple of features that are missing that I wanted to know if nanohttpd is interested in.

Chunked Transfer from Clients - The HTTP/1.1 spec allows both clients and servers to send chunked transfers whenever they want and HTTP/1.1 servers are required to support it. I see that chunked transfer for responses was just added but what about chunked transfer for requests? My use case involves pushing large pieces of parsed data like json between phones so we really don't want to have to manifest them in memory in order to get an accurate data size.

Content Coding - The same vein we would really want support for Content Coding like GZIP. Peer to peer environments are often bandwidth constrained and we move a lot of easily compressible content like JSON around.

Enum free processing for methods and response codes - Right now methods and response codes are identified by enums. But a big part of our project is to provide a generic HTTP environment that can support experimental work with new methods and response codes. So we would like versions of the interface that just provides the method as a string and accepts the response code as a number plus a description.

The last one is pretty easy and unless there are objections at some point I'll just submit a push request for it that should be compatible with the existing interfaces. But the first two are probably not implementable in a way that is compatible with the existing interfaces since they break what's in the input stream in a pretty fundamental way. There are ways to paper over this but only at the cost of buffering everything in memory (or on disk or somewhere) and that sounds like a really bad idea.

That's why I'm bringing this issue up here because I want to understand what y'all are thinking about these ideas and if you have any interest in seeing them tackled given that they probably require interface changes.

Thanks,

  Yaron

Adding ability to serve from multiple homedirs/wwwroots.

Hi,

I required this functionality myself recently - to serve different folders on my disk as a single 'view' on the server.

Used a follows:

java -classpath core\target\classes;webserver\target\classes
    fi.iki.elonen.SimpleWebServer
    -d .
    -d ..\another-folder
    -d c:\somewhere-else

The branch is here, and if you think it would be useful I can submit a pull request.

https://github.com/gitgrimbo/nanohttpd/compare/allow-multiple-homedirs

Thanks for your work on NanoHttpd.

Nanohttpd should be more lenient in processing "Content-Type" and allow comma separators

The original RFC for "Form-based File Upload in HTML" (http://tools.ietf.org/html/rfc1867) gives an example

Content-type: multipart/form-data, boundary=AaB03x

Which erroneously leads to the conclusion that the separator is a comma. In the RFC for "Hypertext Transfer Protocol -- HTTP/1.1" (http://tools.ietf.org/html/rfc2616.html) it is documented that the separator is a semi-colon.

Nanohttpd currently conforms to the spec and is technically correct. However, malformed clients will send a comma and therefore break parsing of the headers and thus multipart file uploads.

Promote Webserver to it's own sub-module

Pull the "Webserver" sample out of the "samples" submodule and promote it to its own sub-module. Be sure to update copyrights, comments and internally identifying strings to reflect its status.

Nanohttpd doesnt handle spaces in uploaded filenames

I modified the file upload test to send 3 files, to verify that uploading more than one file was working. As I was testing I noticed a bug.

3 files as input:

  • 998238db351a3cdbb27fdcbc85c60395.jpeg
  • 01 Zombie.mp3
  • 09-Scooby Doo.mp3

Parameters in "serve()":

  • {datafile2=0, datafile1=998238db351a3cdbb27fdcbc85c60395.jpeg, datafile3=09-Scoob}

Headers in "serve()":

  • {accept-language=en-US,en;q=0.5, content-type=multipart/form-data; boundary=---------------------------295921435817802, connection=keep-alive, accept=text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8, host=localhost:8080, accept-encoding=gzip, deflate, content-length=5860317, user-agent=Mozilla/5.0 (Windows NT 6.1; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0}

It looks like decodeMultipartData() relying on a StringTokenizer using "; " as a delimiter might be incorrectly handling the filenames.

Request headers appear to get corrupted when using ajax post

Simple ajax post requests are handled as expected and requests reach the serve method without issue. However when attempting to set a header from javascript...

xhr.open(...);
xhr.setRequestHeader("SOAPAction", "...");
xhr.send();

The request never makes it to the serve method. Upon debugging the headers as they are read into the hash map they appear corrupted with "SOAPAction" showing as a value not a key. This issue has been identified running on android.

Problem with flash player

I experienced some problems with running flash content on a local server created with NanoHTTPD.
The flash player is definitely present but the swf is never loaded.
I of course checked the path and it that seems good.
The same problem occur with an html page generated with flash itself
Is there some way to enable flash player in NanoHTTPD ?

"No Limit to Listen Threads" Possible security exploit?

Hello,

I've read through some of your code (though not all of it) and it appears you can have as many threads as the system will allow. Couldn't this be exploited into crashing the server? Or is there a way to limit however many connections can be made.

In an attempt to keep things secure, shouldn't there be a, for example, 50 simultaneous thread limit per IP? that way each legit requester will get what they want in a speedy fashion, but most malicious requester will not be as successful at DDOSing the server.

Thanks, MofuJofu

Investigate turn-key install of webserver

What is needed to create a Debian .deb package for install using apt-get?

Can a turn-key install be created that installs and serves files from a fixed location?

Can an install of NanoHttpd be released as a binary for linux platforms?

Can an install of NanoHttpd be released as a binary for Mac / Windows platforms?

Android Sqlite BeginTransaction Deadlock

Succeeding call to the nanohttpd server after Sqlite BeginTransaction (from a previous nanohttpd server call) will result in SqliteConnectionPool deadlock.

Test file: https://gist.github.com/arvinboggs/7922214

Steps to recreate:
1.) Call the nanohttpd serve in Android from another device.
2.) nanohttpd instance should execute an Sqlite BeginTransaction
3.) Again, call the nanohttpd serve in Android from another device.
4.) nanohttpd instance should execute an Sqlite query.
5.) PROBLEM: that query will never finish.

WebServerPlugin doesn't recieve page params

I am trying to connect WebServerPlugin to quercus, a php emulator in Java, and WebServerPlugin doesn't receive the page parms from SimpleWebServer. So I am unable to send them to quercus for proper emulation.

Looking at the code, in SimpleWebServer, the method "respond" should receive the params from the method "serve", so that they can be passed to the plugin when called.

Possibility for multiple servings in a single session

Currently I can get only one serving, when I try to get a second one I get a ProtocolException: Cannot write output after reading input.

I was wondering if it can be made that with a single connections multiple servings can be made. It would make a login system easier

Connection: keep-alive added to response when it shouldn't be

Running load tests with Apache Bench hangs on the first request. This is running the HelloServer.java sample. The issue appears to be that the Connection: keep-alive is always added wether it's needed or not. See this link:

http://www.veebsbraindump.com/2012/03/apache-benchmark-ab-hanging-and-timeout-with-k-keep-alive-switch/

Apache Bench
$ /usr/sbin/ab2 -v 2 -n 100 http://127.0.0.1:8080/
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 127.0.0.1 (be patient)...INFO: POST header ==

GET / HTTP/1.0
Host: 127.0.0.1:8080
User-Agent: ApacheBench/2.3
Accept: /


LOG: header received:
HTTP/1.1 200 OK
Content-Type: text/html
Date: Fri, 12 Jul 2013 16:51:20 GMT
Connection: keep-alive
Content-Length: 144

apr_poll: The timeout specified has expired (70007)

Edit: trying to fix mark up formatting (github newb here)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.