NanoHttpd 构建android 手机端的HttpServer

NanoHttpd是Github上的一个开源项目, 通过下载jar包,新建一个android project, 使用 extends NanoHTTPD 就可以实现一个apk 当WebServer。

示例为显示访问此server的Useragent 和将UA写入文件
import fi.iki.elonen.NanoHTTPD;
public  class UAsetHttpServer extends NanoHTTPD {
    public UAsetHttpServer() throws IOException {
        super(8080);
    }

    @Override
    public Response serve(IHTTPSession session) {

        System.out.println("UAsetHttpServer, method serve start-----");

        String msg = "\n";
        msg += "";
        msg += "\n";

        if(session.getUri().equals("/")){
            String ua = session.getHeaders().get("user-agent");
            System.out.println("UAsetHttpServer, session.getHeaders()-----"+ua);  
            try{
                File file = new File("/data/local/tmp/useragent.txt");
                FileOutputStream fs = new FileOutputStream(file);
                OutputStreamWriter ow = new OutputStreamWriter(fs);
                ow.write(ua);
                ow.close();
                System.out.println("UAsetHttpServer, save useragent to file successfully.");   
            }catch(Exception e){
                System.out.println("UAsetHttpServer, save useragent to file error:"+e.getMessage());  
            }
        }
        return new NanoHTTPD.Response(msg);
    }

}

 调用的地方:

public class AndroidBrowserUAActivity extends Activity {
    private UAsetHttpServer server;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            server = new UAsetHttpServer();
            server.start();
        } catch (IOException e) {
            e.printStackTrace();
            server = null;
        }
    }


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

}

 

当以上的Server起来之后,使用地址http://127.0.0.1:8080/就可以访问。

你可能感兴趣的:(Android)