EzDevInfo.com

nanohttpd

Tiny, easily embeddable HTTP server in Java. NanoHttpd-Project –

NanoHTTPD: determine origin of request

How to determine the IP address that originate the request? My current code:

@Override
public Response serve(String uri, Method method,
    Map<String, String> headers, Map<String, String> parms,
    Map<String, String> files) {

    headers.get("origin"); // my current workaround
};

But any client can modify or remove request headers. So, this is not a proper way to get that information. In ASP.NET MVC3, this is can be achieved via Request.UserHostAddress.


Source: (StackOverflow)

Using NanoHTTPD in Android

I am trying to use NanoHTTP to serve up an HTML file. However, NanoHTTP is relatively un-documented, and I am new to Android. My question is, where do I store the html file, and how specifically can I serve it up using NanoHTTP.


Source: (StackOverflow)

Advertisements

NanoHttpd server cannot stream large videos on android

NanoHttpd server code can be found here.

I'm starting a new Thread in a service that uses NanoHttpd server to stream large videos (about 150mb) but it just pauses right while the loading dialog is shown. I tried increasing and decreasing the buffer reads to no avail. It seems that the server cannot run properly on an Android device.

Same code works fine when I start the server via desktop application. I can stream more than 150mb. When running the server from the phone, I only tried 20mb files and they were good too. However I need to stream much more than that.


Source: (StackOverflow)

Store, convert to video an stream Android screen

I use DDMS to get screenshots from my Android phone and I need an efficient way for converting them in video and streaming the video over the network.

I have a RawImage which is filled with the data of the screenshot:

RawImage mRawImage;

Until know I use SWT to create the image and save it:

PaletteData paletteData = new PaletteData(
    mRawImage.getRedMask(),
    mRawImage.getGreenMask(),
    mRawImage.getBlueMask());

ImageData imageData = new ImageData(
    mRawImage.width,
    mRawImage.height,
    mRawImage.bpp,
    paletteData,
    1,
    mRawImage.data);

ImageLoader s = new ImageLoader();
s.data = new ImageData[] {imageData};
s.save("temp.jpg",SWT.IMAGE_JPEG);
  • Can you propose a way to convert those images sequence to video and then stream the video?

I found NanoHTTPD which can be used for streaming but how can I convert and compress the images to video?

  • Do you believe that I can do that using ffmpeg?

I found a good Tutorial for streaming your webcam using FFMPEG and video4linux2.

Is it possible to send the bytes from the RawImage to the FFMPEG to be converted to a live video stream?

Actual code:

$ffmpeg -f video4linux2 -i /dev/video0 http://78.47.18.19:8090/cam1.ffm

Replace it with something similar to:

$ffmpeg -f video4linux2 -i **<add here java stream>** http://78.47.18.19:8090/cam1.ffm

Any suggestions?

Thanks

PS: I expect a solution which will help me convert the images to a compressed video and then stream the video over the network in order to play it with either HTML5 or a Flash Player


Source: (StackOverflow)

Retrieve HTTP Body in NanoHTTPD

How can I retrieve the HTTP POST request body when implementing NanoHTTPDs serve method?

I've tried to use the getInputStream() method of IHTTPSession already, but I always get an SocketTimeoutException when using it inside of the serve method.


Source: (StackOverflow)

How to analyze httpd (apache webserver) logs in CentOS 7

I have configred a static IP on my server that is using CentOS 7. Here httpd is the webserver. Now I have to analyze following things.

  1. Total number of queries per day (or toall)
  2. Total requests sent and served.
  3. Unique visitors details
  4. List of queries recieved. (status etc.)
  5. HOSTs/OS/Browsers that request for query
  6. Errors etc.
  7. Should be able to save it in CSV etc. format so that I can import it to excel.

Can anyone suggest me some log analyzer that will fullfill above requirements ?


Source: (StackOverflow)

Android Http server and broken pipes

I'm trying to develop an Android UPnP application that has an embedded http server in it, so it can serve media files from the device over lan.

The first implementacion of the web server that I used was based on the ElementalHttpServer example from Apache HttpCore http://hc.apache.org/httpcomponents-core-ga/index.html. It had to be changed a little bit because the org.apache.http elements that are already included in the Android library differed from the latest included in the httpCore jar.

I tried to substitute the Android ones with the ones from the jar but that couldn't be done - the ones in the Android library have the priority. When I change the library order there was a problem with duplicate classes.

Than instead of the jars I included source code and change the packet names to avoid duplicated classes problem.

The problem with the broken pipe and connection problems persisted.

I've also tried the NHttpServer from HttpCoreNIO since it has different set of classes than the basic httpCore and could be included and used without conflicting with the httpCore in the Android itself.

Then I used NanoHTTPD which seems to work the best of all the http servers so fat but is still troubled by the same problem as all the others:

java.net.SocketException: The connection was reset
at org.apache.harmony.luni.platform.OSNetworkSystem.sendStreamImpl(Native Method)
at org.apache.harmony.luni.platform.OSNetworkSystem.sendStream(OSNetworkSystem.java:498)
at org.apache.harmony.luni.net.PlainSocketImpl.write(PlainSocketImpl.java:585)
at org.apache.harmony.luni.net.SocketOutputStream.write(SocketOutputStream.java:59)
at com.zappotv.network.http.NanoHTTPD$HTTPSession.sendResponse(NanoHTTPD.java:828)
at com.zappotv.network.http.NanoHTTPD$HTTPSession.run(NanoHTTPD.java:478)
at java.lang.Thread.run(Thread.java:1096)

and

java.net.SocketException: Broken pipe
at org.apache.harmony.luni.platform.OSNetworkSystem.sendStreamImpl(Native Method)
at org.apache.harmony.luni.platform.OSNetworkSystem.sendStream(OSNetworkSystem.java:498)
at org.apache.harmony.luni.net.PlainSocketImpl.write(PlainSocketImpl.java:585)
at org.apache.harmony.luni.net.SocketOutputStream.write(SocketOutputStream.java:59)
at com.zappotv.network.http.NanoHTTPD$HTTPSession.sendResponse(NanoHTTPD.java:828)
at com.zappotv.network.http.NanoHTTPD$HTTPSession.run(NanoHTTPD.java:478)
at java.lang.Thread.run(Thread.java:1096)

Recently I have implemented iJetty into the app but the problem still persists. Sometimes the requesting device goes into an endless loop of requests.

What could I be doing wrong? May the headers be a problem ?


Source: (StackOverflow)

How to serve a file on sdcard using NanoHTTPD (inside Android)

I've written a small Android server using NanoHTTPD. It can serve an HTML file well (web page located at sdcard/www/index.html). Can anybody please help me find out how can I serve an audio or video file instead of an html page using NanoHTTPD? Forgive me if the question seems silly, as I'm new to HTTP! Here is my server side code (I've replaced the webpage path to that of an audio file):

package com.example.zserver;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;

public class MainActivity extends Activity {

    private WebServer server;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        server = new WebServer();
        try {
            server.start();
        } catch(IOException ioe) {
            Log.w("Httpd", "The server could not start.");
        }
        Log.w("Httpd", "Web server initialized.");

    }
    @Override
    public void onDestroy()
    {
        super.onDestroy();
        if (server != null)
            server.stop();
    }

    private class WebServer extends NanoHTTPD {

        public WebServer()
        {
            super(8080);
        }

        @Override
        public Response serve(String uri, Method method, 
                              Map<String, String> header,
                              Map<String, String> parameters,
                              Map<String, String> files) {
            String answer = "";
            try {
                // Opening file from SD Card
                File root = Environment.getExternalStorageDirectory();
                FileReader index = new FileReader(root.getAbsolutePath() +
                        "/www/music.mp3");              
                BufferedReader reader = new BufferedReader(index);
                String line = "";
                while ((line = reader.readLine()) != null) {
                    answer += line;
                }

            } catch(IOException ioe) {
                Log.w("Httpd", ioe.toString());
            }


            return new NanoHTTPD.Response(answer);
        }
    }

}

I've included necessary use-permissions in my code:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Any help would be appreciated. Thanks in advance!

EDIT, Added permission:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

EDIT1: Canonical way of reading and writing to buffers:

int read;
        int n=1;
        while((read = dis.read(mybytearray)) != -1){
            dos.write(mybytearray, 0, read);}

Source: (StackOverflow)

Why RMI registry is ignoring the java.rmi.server.codebase property

I am running a Hello World example for java RMI

1) I run the registry in an empty folder

motta@motta-laptop ~/tmp $ rmiregistry

2) I start the HTTP server to retrieve the classes at runtime. The download folder contains the remote interface for the client-server

motta@motta-laptop ~/download $ java NanoHTTPD 8080

3) I start the server passing the java.rmi.server.codebase property as suggested in the java RMI tutorial

motta@motta-laptop ~/server $ java -Djava.rmi.server.codebase="http://localhost:8080" WarehouseServer

The RMI registry is not contacting the HTTP server and is throwing an exception (see details after the question). But if I do the following

1) Start the rmi registry with the java.rmi.server.codebase property

motta@motta-laptop ~/tmp $ rmiregistry -J-Djava.rmi.server.codebase="http://localhost:8080/"

2) Start the HTTP server as before

3) Start the server without any option

motta@motta-laptop ~/server $ java WarehouseServer

it works, but why? It seems that with the first procedure the RMI registry is ignoring the java.rmi.server.codebase property

Thank you

=================================

I am running

java version "1.7.0_21"
Java(TM) SE Runtime Environment (build 1.7.0_21-b11)
Java HotSpot(TM) 64-Bit Server VM (build 23.21-b01, mixed mode)

The exception from the RMI registry

Constructing server implementation...
Binding server implementation to registry...
Exception in thread "main" java.rmi.ServerException: RemoteException occurred in server thread; nested exception is: 
java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is: 
java.lang.ClassNotFoundException: Warehouse
at sun.rmi.server.UnicastServerRef.oldDispatch(UnicastServerRef.java:419)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:267)
at sun.rmi.transport.Transport$1.run(Transport.java:177)
at sun.rmi.transport.Transport$1.run(Transport.java:174)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:173)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:553)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:808)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:667)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)
at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:273)
at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:251)
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:377)
at sun.rmi.registry.RegistryImpl_Stub.bind(Unknown Source)
at WarehouseServer.main(WarehouseServer.java:14)

Source: (StackOverflow)

how to stream video from internet via nanoHTTPd to VideoView

I want to download and play video files during downloading. Since VideoView is not helping with this matter I decided to work with nanoHTTPd to create a pseudo HTTP server and inside my own server try to download video file and play it afterward but my problem is :

1-How can I flush downloaded part to videoview and download the remaining parts?

Following is my source :

public class VideoStreamingServer extends NanoHTTPD {

        public VideoStreamingServer() {
            // by default listening on port 8080
            super(8080);
        }

        @Override
        public Response serve(String URI, Method method,
                              Map header, Map parameters, Map files) {

            FileInputStream fis = null;
            try {
//                fis = new FileInputStream("/mnt/sdcard/p/1.mp4");

                File bufferFile = File.createTempFile("test", "mp4");

                BufferedOutputStream bufferOS = new BufferedOutputStream(
                        new FileOutputStream(bufferFile));

                HttpClient client = new DefaultHttpClient();
                HttpGet request = new HttpGet("http://www.example.net/dl/1.mp4");
                HttpResponse response = client.execute(request);
                Header[] headers = response.getAllHeaders();
                Log.e("Internet buffer", "connected to server");

                BufferedInputStream bis = new BufferedInputStream(response.getEntity().getContent(), 2048);


                byte[] buffer = new byte[16384];
                int numRead;
                boolean started = false;
                while ((numRead = bis.read(buffer)) != -1) {

                    bufferOS.write(buffer, 0, numRead);
                    bufferOS.flush();
                    totalRead += numRead;
                    if (totalRead > 120000 && !started) {
                             //problem starts here
                             //How can I flush the buffer to VideoView?


                    }

                }


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


            return new NanoHTTPD.Response(Response.Status.OK, "video/mp4", fis);
        }
    }

Source: (StackOverflow)

NanoHTTPD. Cache InputStream to file and continue streaming


I want to cache data while playing it in MediaPlayer. As I read, there is one way to do it - create own local http server and set local url to MediaPlayer's setDataSource(String path).

I am using NanoHTTPD as a local server. There is code of serve function:


    @Override
    public Response serve(String uri, Method method, Map headers, Map parms, Map files)
    {
        try
        {
            // delete / character
            URL url = new URL(uri.substring(1));
            URLConnection connection = url.openConnection();
            connection.connect();

            File cacheFolder = new File(Environment.getExternalStorageDirectory(), "TracksFlowCacheNew");
            Log.e("RelayServer", "Cache to file " + Utils.md5(url.toExternalForm()));
            RelayInputStream ris = new RelayInputStream(connection.getInputStream(), new FileOutputStream(new File(cacheFolder, Utils.md5(url.toExternalForm()))));


            return new Response(Response.Status.OK, NanoHTTPD.MIME_DEFAULT_BINARY, ris);
        }
        catch(MalformedURLException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch(FileNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch(IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }


RelayInputStream extending InputStream. I am trying to cache data there:


    private class RelayInputStream extends InputStream
    {
        private InputStream mInputStream = null;
        private OutputStream mOutputStream = null;

        public RelayInputStream(InputStream is, OutputStream os)
        {
            mInputStream = is;
            mOutputStream = os;
        }

        @Override
        public int available() throws IOException
        {
            Log.e("available", "available = " + mInputStream.available());
            mInputStream.mark(mInputStream.available());
            return mInputStream.available();
        }

        @Override
        public int read(byte[] buffer) throws IOException
        {
            Log.e("read", "buffer = " + buffer.toString());
            mOutputStream.write(buffer);
            return mInputStream.read(buffer);
        }

        @Override
        public int read(byte[] buffer, int offset, int length) throws IOException
        {
            Log.e("read", "buffer = " + buffer.toString() + "; offset = " + offset + "; length = " + length);
            mOutputStream.write(buffer, offset, length);
            return mInputStream.read(buffer, offset, length);
        }

        @Override
        public int read() throws IOException
        {
            Log.e("read", "no data");
            byte[] b = new byte[1];
            mInputStream.read(b);
            mOutputStream.write(b);
            mInputStream.close();
            mOutputStream.close();
            return b[0] & 0xff;
        }
    }

But RelayInputStream's available returns only few downloaded bytes. So, there is only little part of data cached and returned to the media player. So, what am I doing wrong? How to forward and cache all stream?


Source: (StackOverflow)

Reading InputStream of NANOHTTPD gives Socket TimeOut Exception

I am trying to read the InputStream from IHTTPSession.getInputStream() using the following code but its gives Socket TimeOut Exception every time.

private String readInStream(InputStream in){

        StringBuffer outBuffer=new StringBuffer();
        BufferedInputStream bis=new BufferedInputStream(in);
        try {
            while(bis.available()>0){
                int ch= bis.read();
                outBuffer.append((char)ch);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Log.e("DATA_Length", "outputBuffer :"+outBuffer.toString().length());
        return outBuffer.toString();
    }

i also tried the following Method but the same exception arises

private String readInStream(InputStream in){
        String line="";
        StringBuffer outBuffer=new StringBuffer();

        BufferedReader rd=new BufferedReader(new InputStreamReader(in));

        try {
            while((line=rd.readLine()) != null){
                outBuffer.append(line);
            }
        } catch (IOException e) {
            Log.e("IOException", "IOException in readInStream:");
            e.printStackTrace();
        }

        Log.e("DATA_Length", "outputBuffer :"+outBuffer.toString().length());
        return outBuffer.toString();
    }

Source: (StackOverflow)

How to create an http server on android that a desktop can access (vice-versa) using NanoHTTPD

Using an available WiFi IP (i.e. 192.xxx.x.x, using post 8080), I'd like to create a http server in android that can connect and can be accessed by a desktop so that I can transfer files to the android device.

Update: I'm currently trying out NanoHTTPD but I can't seem to make the sample HelloWorld run on android device..

I changed the hello world code and made it extend activity instead and created an object nanohttpd.

I modified up to specifying what port to be used but upon further debugging, I found out that the server socket has no getInetAddress at all. I thought NanoHTTPD no longer needs further config...?


Source: (StackOverflow)

Keep Android awake for incoming network connections?

I'm writing an HTTP server for Android devices, implemented via NanoHTTPD.

A goal of mine is to have the device allow incoming connections even with the screen off.

I started small, with a persistent notification, thinking that would keep my app in memory and running in the background. After locking the device, I could keep navigating the webpages it serves up as long as I don't leave it alone for about a minute. Once I do, it totally stops responding.

I escalated my attempt by including a CPU partial wakelock, which made no difference. I then added a full WifiLock to keep the radio on, and finally, in desperation, a MulticastLock (I thought maybe it'd keep the radio listening for connections). Still, after not making any connections for about a minute, the device stops responding, even with all these locks.

Is there anything specific I can do to keep the device listening for incoming connections? It seems like hitting the device with periodic requests keeps it awake... can I somehow emulate this behavior programmatically? I cannot think of a way.

Thanks!

EDIT: for the purpose of this question, battery drain can be disregarded.

EDIT: NanoHTTPD is being run as a service, as well.


Source: (StackOverflow)

Use NanoHTTPD a proxy while streaming

I want to cache a stream before feeding it to Androids mediaplayer. My idea is to feed the android mediaplayer a link to nanohttpd which will then open a connection to the remote webserver and forward the stream to the mediaplayer. Meanwhile I will cache the stream, but this is not implemented yet since the first part doesn't work.

The main problem is that the mediaplayer only seems to receive the first few bytes before the stream is closed. Any idea what I'm doing wrong?

Here is the relevant code:

@Override
public Response serve(String uri, Method method, Map<String, String> header, Map<String, String> parms, Map<String, String> files) {
    String stringurl = parms.get(HTTPDService.key);

    if (stringurl != null) {

    // Initialize variables
    URL url = null;
    HttpURLConnection connection = null;
    InputStream in = null;

    // Open the HTTP connection
    try {
        url = new URL(stringurl);
        connection = (HttpURLConnection) url.openConnection();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
      // Read the response.
      in = connection.getInputStream();
    } catch (IOException e) {
        e.printStackTrace();
    }


    String datatype = connection.getContentType(); //NanoHTTPD.MIME_DEFAULT_BINARY
    return new NanoHTTPD.Response(Status.ACCEPTED, datatype, in);
}

EDIT I just found the same question (unanswered) here: NanoHTTPD. Cache InputStream to file and continue streaming


Source: (StackOverflow)