问题
Actually ,I had searched some questions and go to the github. But I'm new ,I cannot understand the example.
I want to create the http server in android so I can access it in PC browser.
I had instance a class extend nanohttpd, but the server just don't work. I don't know why ,my computer and phone are in the same WIFI,uh.....
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");
};
}
}
回答1:
Your sample code is missing one small detail - you create the server but you never call the "start()" method which kicks it off to listen for incoming connections. In your main() method, you could write
(new MyHTTPD()).start();
and all would be well, your server would respond the way you hoped it would.
The reason it works that way is twofold: I want the constructor to be a cheap, inexpensive operation, without side-effects. For instance, while unit testing, I call "start()" in the setup and "stop()" in the teardown methods of my jUnit test.
回答2:
This is the code working for me, but I have different version of NANOHTTPD, I don't have time right now to test out your solution. Here is UploadServer class and Nano class. I return file-upload.htm from sdcard/Discover Control/Web path
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 class
NanoHTTPD.java
FILE UPLOAD
file-upload.htm
Hope this helps and enjoy your work.
回答3:
Android Activities have a lifecycle and do not use a main()
function.
If you want to start and stop the webserver as part of the Activity then you need call start and stop
in onPause
and onResume
, ie
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;
}
}
}
An alternative is to implement the webserver as part of a Service.
In an app I'm working I have a requirement to keep the webserver running even if the user leaves the app. The only way to do this is to start and stop the webserver as part of a long-running Service that is not bound to the Activity. See Vogella's great tutorial on Android Services.
回答4:
This code working for fine viewing html pages with css class which are in my assesst folders
androidWebServer.start();
this will start the server below code for server functions
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);
}
来源:https://stackoverflow.com/questions/16560285/how-to-create-nanohttpd-server-in-android