我想在android中创建一个Simple Http服务器

时间:2015-03-30 14:21:57

标签: android http server

我已使用https://github.com/NanoHttpd/nanohttpd代码作为参考。 当我运行我的简单的Android应用程序。我得到了#34;应用程序不受支持"错误。在eclipse中运行我的android应用程序。

我的主要活动代码是:

package com.example.nanoservertest;


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

import java.util.Map;
import java.util.Properties;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;

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

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

  @Override
  protected void onResume() {
    super.onResume();
    System.out.println("inside resume");
 try {
      server = new MyHTTPD();
      server.stratServer();
      //server.start();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

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

    //Start
    public void stratServer(){
    ServerRunner.run(MyHTTPD.class);
    }

    @Override
    public Response serve(IHTTPSession session) {
        Method method = session.getMethod();
        String uri = session.getUri();
        System.out.println(method + " '" + uri + "' ");

        String msg = "<html><body><h1>Hello server</h1>\n";
        Map<String, String> parms = session.getParms();
        if (parms.get("username") == null)
            msg +=
                    "<form action='?' method='get'>\n" +
                            "  <p>Your name: <input type='text' name='username'></p>\n" +
                            "</form>\n";
        else
            msg += "<p>Hello, " + parms.get("username") + "!</p>";

        msg += "</body></html>\n";

        return new NanoHTTPD.Response(msg);
    }
  }
}

我的服务器运行者类是

import java.io.IOException;

public class ServerRunner {
    public static void run(Class serverClass) {
        try {
            executeInstance((NanoHTTPD) serverClass.newInstance());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void executeInstance(NanoHTTPD server) {
        try {
            server.start();
        } catch (IOException ioe) {
            System.err.println("Couldn't start server:\n" + ioe);
            System.exit(-1);
        }

        System.out.println("Server started, Hit Enter to stop.\n");

        try {
            System.in.read();
        } catch (Throwable ignored) {
        }

        server.stop();
        System.out.println("Server stopped.\n");
    }
}

我无法启动我的申请。

1 个答案:

答案 0 :(得分:0)

尝试使用此库,它似乎响应您的需求: AndroidAsync