7

实际上,我已经搜索了一些问题并去了 github。但我是新手,我看不懂这个例子。

我想在 android 中创建 http 服务器,以便可以在 PC 浏览器中访问它。

我有一个类扩展 nanohttpd 的实例,但服务器无法正常工作。我不知道为什么,我的电脑和手机在同一个WIFI,呃......

public class MyHTTPD extends NanoHTTPD {

     /**
     * Constructs an HTTP server on given port.
     */
    public MyHTTPD()throws IOException {
        super(8080);
    }


@Override
    public Response serve( String uri, Method method,
            Map<String, String> header, Map<String, String> parms,
            Map<String, String> files )
    {
        System.out.println( method + " '222" + uri + "' " );
        String msg = "<html><body><h1>Hello server</h1>\n";
        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 );
    }


    public static void main( String[] args )
    {
        try
        {
            new MyHTTPD();
        }
        catch( IOException ioe )
        {
            System.err.println( "Couldn't start server:\n" + ioe );
            System.exit( -1 );
        }
        System.out.println( "Listening on port 8080. Hit Enter to stop.\n" );
        try { System.in.read(); } catch( Throwable t ) {
            System.out.println("read error");
        };
    }

}
4

4 回答 4

11

您的示例代码缺少一个小细节 - 您创建了服务器,但您从未调用“start()”方法来启动它以侦听传入连接。在您的 main() 方法中,您可以编写

        (new MyHTTPD()).start();

一切都会好起来的,您的服务器会按照您希望的方式响应。

它以这种方式工作的原因有两个:我希望构造函数是一种廉价、廉价的操作,没有副作用。例如,在单元测试时,我在设置中调用“start()”,在jUnit 测试的拆卸方法中调用“stop()” 。

于 2013-05-21T04:17:21.827 回答
0

这是为我工作的代码,但我有不同版本的 NANOHTTPD,我现在没有时间测试你的解决方案。这是 UploadServer 类和 Nano 类。我从 sdcard/Discover Control/Web 路径返回 file-upload.htm

public class UploadServer extends NanoHTTPD {
public UploadServer() throws IOException {
    super(8080, new File("."));
}

public Response serve( String uri, String method, Properties header, Properties parms, Properties files ) {
    File rootsd = Environment.getExternalStorageDirectory();
    File path = new File(rootsd.getAbsolutePath() + "/Discover Control/Web");
    Response r = super.serveFile("/file-upload.htm", header, path, true);
    return r;
}
}

NanoHttpd 类

NanoHTTPD.java

上传文件

文件上传.htm

希望这对您有所帮助并享受您的工作。

于 2013-05-15T10:17:33.320 回答
0

Android 活动有生命周期,不使用main()函数。

如果您想在 Activity 中启动和停止网络服务器,那么您需要在 and 中调用 start 和 stop onPauseonResume

public class MyActivity extends Activity {

    private MyHTTPD mServer;

    @Override
    protected void onResume() {
        super.onResume();

       try {
            mServer = new MyHTTPD();
            mServer.start();
        } catch (IOException e) {
            e.printStackTrace();
            mServer = null;
        }


    @Override
    protected void onPause() {
        super.onPause();
        if(mServer != null) {
            mServer.stop();
            mServer = null;
        }
    }
}

另一种方法是将网络服务器实现为服务的一部分。

在我正在工作的应用程序中,即使用户离开应用程序,我也需要保持网络服务器运行。做到这一点的唯一方法是启动和停止 web 服务器作为未绑定到 Activity 的长期运行服务的一部分。请参阅Vogella 关于 Android 服务的精彩教程

于 2014-12-16T18:52:41.430 回答
0

此代码适用于在我的评估文件夹中查看带有 css 类的 html 页面

androidWebServer.start();

这将在服务器功能的代码下面启动服务器

public class AndroidWebServer extends NanoHTTPD {

Realm realm;

Map<String, String> parms;
DBHelper db = new DBHelper(OpenRAP.getContext());
boolean isStartedHS = MainActivity.isStartedHS;
private AsyncHttpServer server = new AsyncHttpServer();
private AsyncServer mAsyncServer = new AsyncServer();
private String TAG = "androidwebserver";
Storage storage = new Storage(OpenRAP.getContext());
public AndroidWebServer(int port) {
    super(port);
}


public AndroidWebServer(String hostname, int port) {
    super(hostname, port);
}


@Override
public String getHostname() {
    return super.getHostname();
}


@Override
public Response serve(IHTTPSession session) {
    Method method = session.getMethod();
    String uri = session.getUri();
    Map<String, String> files = new HashMap<>();
    SharedPreferences prefs = OpenRAP.getContext().getSharedPreferences(MainActivity.mypreference, MODE_PRIVATE);
    OpenRAP app = (OpenRAP) OpenRAP.getContext();
    Storage storage = new Storage(OpenRAP.getContext());
    String currentpath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/www/";
    String temp = Environment.getExternalStorageDirectory().getAbsolutePath() + "/www/temp/";
    String ecarpath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/www/ecars_files/";
    String xcontent = Environment.getExternalStorageDirectory().getAbsolutePath() + "/www/xcontent/";
    String Endpoint = session.getUri();
    if (Endpoint.equals("/")) {

        String answer = "";
        try {
            // Open file from SD Card
            File root = Environment.getExternalStorageDirectory().getAbsoluteFile();
            FileReader index = new FileReader(root +
                    "/www/openrap/index.html");
            BufferedReader reader = new BufferedReader(index);
            String line = "";
            while ((line = reader.readLine()) != null) {
                answer += line;
            }
            reader.close();
        } catch (IOException ioe) {
            Log.w("Httpd", ioe.toString());
        }
        return newFixedLengthResponse(answer);
    }
于 2018-12-07T06:53:19.030 回答