Jun*_*ong 6 android http nanohttpd
实际上,我搜索了一些问题然后去了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");
};
}
}
Run Code Online (Sandbox Code Playgroud)
Pau*_*wke 10
您的示例代码缺少一个小细节 - 您创建服务器但您从未调用"start()"方法,该方法将其启动以侦听传入连接.在你的main()方法中,你可以写
(new MyHTTPD()).start();
Run Code Online (Sandbox Code Playgroud)
一切都会好的,你的服务器会以你希望的方式响应.
它以这种方式工作的原因有两个:我希望构造函数是一种廉价,廉价的操作,没有副作用.例如,在单元测试时,我在设置中调用"start()",在我的jUnit测试的拆卸方法中调用" stop()" .
这是适合我的代码,但我有不同版本的 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;
}
}
Run Code Online (Sandbox Code Playgroud)
NanoHttpd 类
上传文件
希望这对您有所帮助并享受您的工作。
| 归档时间: |
|
| 查看次数: |
15187 次 |
| 最近记录: |