Android NanoHTTPD not working
I am trying to create a simple android server application and I am very
low on time so i thought I should give NanoHTTPD a try. I have added
NanoHTTPD.java file directly to my namespace and the following code below
works and launches perfectly but when I do an HTTP POST with a client
using asynchttp nothing happens. I am able to ping the IP and it seems to
be working.
import java.io.IOException;
import java.util.Map;
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.util.Log;
import android.widget.TextView;
import com.ahmad.simplewebserver.NanoHTTPD.Response.Status;
public class MainActivity extends Activity {
private static final int PORT = 8765;
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();
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);
}
@Override
public Response serve(String uri, Method method, Map<String,
String> headers,
Map<String, String> parms, Map<String, String> files) {
Log.i("Testing", "Http Serve");
final StringBuilder buf = new StringBuilder();
for (Entry<String, String> kv : headers.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(Status.OK, MIME_HTML, html);
}
}
}
No comments:
Post a Comment