3

我试图让 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 文件。有任何想法吗?

4

1 回答 1

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 卡。

看看是否有帮助。

于 2013-07-19T21:34:47.447 回答