0

我厌倦了用 nanoHTTPD 运行简单的 android 示例。当我在模拟器中运行程序时,它显示http://xxx.xxx.xxx.xxx:8080。如果我在设备中运行相同的程序,它会显示一个 IP 地址http://xxx.xxx.xxx.xxx:8080。我在移动浏览器和我的网络浏览器中尝试了这些 ip。它显示页面无法显示错误。我按照这个例子https://gist.github.com/komamitsu/1893396

这是我的代码。

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);
    }
  }
}

提前致谢。谁能告诉我我必须做出什么改变才能得到正确的结果。

4

2 回答 2

0

您需要调用 server.start() 来实际启动服务器

于 2014-08-08T13:27:51.777 回答
0

我想你忘了启动服务器...

try { 
      server = new MyHTTPD();
      server.start();
    } catch (IOException e) {
      e.printStackTrace();
    } 
于 2016-11-28T13:00:43.997 回答