0

I tired to run the simple example of android with nanoHTTPD. when i run the program in emulator it shows http://xxx.xxx.xxx.xxx:8080. If i run the same program in device it shows an ip address http://xxx.xxx.xxx.xxx:8080. I tried those ip in the mobile browser and in my web browser. it shows page cannot be displayed error. I followed this example https://gist.github.com/komamitsu/1893396

This is my code.

package com.komamitsu;

import java.io.IOException;
import java.util.Map.Entry;
import java.util.Properties;

import android.app.Activity;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;

public class AndroidWebServerActivity extends Activity {
  private static final int PORT = 8080;
  private TextView hello;
  private MyHTTPD server;
  private Handler handler = new Handler();

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    hello = (TextView) findViewById(R.id.hello);
  }

  @Override
  protected void onResume() {
    super.onResume();

    TextView textIpaddr = (TextView) findViewById(R.id.ipaddr);
    WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
    int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
    final String formatedIpAddress = String.format("%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff),
        (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
    textIpaddr.setText("Please access! http://" + formatedIpAddress + ":" + PORT);

    try {
      server = new MyHTTPD();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

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

  private class MyHTTPD extends NanoHTTPD {
    public MyHTTPD() throws IOException {
      super(PORT, null);
    }

    @Override
    public Response serve(String uri, String method, Properties header, Properties parms, Properties files) {
      final StringBuilder buf = new StringBuilder();
      for (Entry<Object, Object> kv : header.entrySet())
        buf.append(kv.getKey() + " : " + kv.getValue() + "\n");
      handler.post(new Runnable() {
        @Override
        public void run() {
          hello.setText(buf);
        }
      });

      final String html = "<html><head><head><body><h1>Hello, World</h1></body></html>";
      return new NanoHTTPD.Response(HTTP_OK, MIME_HTML, html);
    }
  }
}

Thanks in advance. Can anyone tell me what change that i have to made to get the correct result.

Prabhu
  • 840
  • 11
  • 28

2 Answers2

0

You need to call server.start() to actually start the server

Makubex
  • 1,054
  • 1
  • 9
  • 16
0

i think you forgot to start the server...

try { 
      server = new MyHTTPD();
      server.start();
    } catch (IOException e) {
      e.printStackTrace();
    } 
froyohuang
  • 56
  • 3