Android-->原生API搭建Android Http服务器

代码很简单….都不知道怎么写了

就一个类,复制粘贴就能使用

声明一个类 WebServer extends Thread

public class WebServer extends Thread {
    private boolean isRunning = false;
    private Context context = null;
    private int serverPort = 0;

    private BasicHttpProcessor httpproc = null;
    private BasicHttpContext httpContext = null;
    private HttpService httpService = null;
    private HttpRequestHandlerRegistry registry = null;

    public WebServer(Context context) {
        super(SERVER_NAME);

        this.setContext(context);

        serverPort = 8080;
        httpproc = new BasicHttpProcessor();
        httpContext = new BasicHttpContext();

        httpproc.addInterceptor(new ResponseDate());
        httpproc.addInterceptor(new ResponseServer());
        httpproc.addInterceptor(new ResponseContent());
        httpproc.addInterceptor(new ResponseConnControl());

        httpService = new HttpService(httpproc,
                new DefaultConnectionReuseStrategy(),
                new DefaultHttpResponseFactory());

        registry = new HttpRequestHandlerRegistry();

        registry.register("/rsen*", new HttpRequestHandler() {

            @Override
            public void handle(final HttpRequest request,
                    HttpResponse response, HttpContext context)
                    throws HttpException, IOException {//处理请求的地方

                HttpEntity entity = new EntityTemplate(new ContentProducer() {

                    @Override
                    public void writeTo(OutputStream outstream)
                            throws IOException {
                        OutputStreamWriter writer = new OutputStreamWriter(
                                outstream);
                        // outstream.write(request.getRequestLine().getUri().getBytes());
                        String command = Uri.decode(request.getRequestLine()
                                .getUri());
                        writer.write("命令:rsen\n");
                        writer.write("参数:");
                        if (command.length() > 6 && command.charAt(5) == '?') {
                            for (Map.Entry<String, String> set : getParams(
                                    command.substring(6)).entrySet()) {
                                writer.write("\n" + set.getKey() + ":"
                                        + set.getValue() + "\n");
                            }
                        } else {
                            writer.write("无参数!");
                        }

                        writer.flush();
                    }
                });

                response.setEntity(entity);
            }
        });

        httpService.setHandlerResolver(registry);
    }

    Map<String, String> getParams(String string) {
        Map<String, String> params = new HashMap<String, String>();
        String[] strs = string.split("&");
        String[] pars;
        for (String str : strs) {
            pars = str.split("=");
            params.put(pars[0], pars.length > 1 ? pars[1] : "");
        }
        return params;
    }

    @Override
    public void run() {
        super.run();

        try {
            ServerSocket serverSocket = new ServerSocket(serverPort);

            serverSocket.setReuseAddress(true);

            while (isRunning) {
                try {
                    final Socket socket = serverSocket.accept();

                    DefaultHttpServerConnection serverConnection = new DefaultHttpServerConnection();

                    serverConnection.bind(socket, new BasicHttpParams());

                    httpService.handleRequest(serverConnection, httpContext);

                    serverConnection.shutdown();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (HttpException e) {
                    e.printStackTrace();
                }
            }

            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public synchronized void startThread() {
        if (!isRunning) {
            isRunning = true;
            super.start();
        }
    }

    public synchronized void stopThread() {
        isRunning = false;
    }

    public void setContext(Context context) {
        this.context = context;
    }

    public Context getContext() {
        return context;
    }
}

就是这么简单;

源码地址: http://download.csdn.net/detail/angcyo/8796243

至此: 文章就结束了,如有疑问: QQ群:274306954 欢迎您的加入.

你可能感兴趣的:(android,HTTP服务器)