首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Android NANOHTTPD问题?

Android NANOHTTPD问题?
EN

Stack Overflow用户
提问于 2013-10-03 14:57:29
回答 2查看 991关注 0票数 0

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

这是我的代码。

代码语言:javascript
复制
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);
    }
  }
}

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

EN

回答 2

Stack Overflow用户

发布于 2014-08-08 21:27:52

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

票数 0
EN

Stack Overflow用户

发布于 2016-11-28 21:00:44

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

代码语言:javascript
复制
try { 
      server = new MyHTTPD();
      server.start();
    } catch (IOException e) {
      e.printStackTrace();
    } 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19152721

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档