android中的nanohttpd不会工作

时间:2013-07-16 18:24:09

标签: android nanohttpd

我试图让nanohttpd在android下工作。我用过这个例子:

package com.example.android_test;

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

import com.example.android_test.NanoHTTPD.Response.Status;

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

public class MainActivity extends Activity {
  private static final int PORT = 8765;
  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);
    }

    @Override
    public Response serve(String uri, Method method, Map<String, String> headers,
        Map<String, String> parms, Map<String, String> files) {
      final StringBuilder buf = new StringBuilder();
      for (Entry<String, String> kv : headers.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(Status.OK, MIME_HTML, html);
    }
  }
}

当我在手机上启动应用程序时,活动会显示正确的IP地址。我也可以ping显示的地址。但是,当我尝试通过浏览器访问此网站时,该网站将无法加载。另外上面显示的MainActivity.java我只添加了nanohttpd项目中的NanoHTTPD.java文件。有什么想法吗?

1 个答案:

答案 0 :(得分:7)

有两件事情可以想到,两者都是权限相关的。看看你的Android清单,你需要两个你的应用程序的权限

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

INTERNET,因为您正在访问网络服务和WRITE_EXTERNAL_STORAGE,因为当NanoHttpd收到传入连接时,它会写入临时文件,而大多数/所有手机都会将“java.io.tmpdir”映射到指向SD卡。

看看是否有帮助。