java wiki - apache httpserver and httpclient

Server case

public class ElementalHttpServer {  
  
    public static void main(String[] args) throws Exception {  
        if (args.length < 1) {  
            System.err.println("Please specify document root directory");  
            System.exit(1);  
        }  
        Thread t = new RequestListenerThread(8080, args[0]);  
        t.setDaemon(false);  
        t.start();  
    }  
  
    static class HttpFileHandler implements HttpRequestHandler  {  
  
        private final String docRoot;  
  
        public HttpFileHandler(final String docRoot) {  
            super();  
            this.docRoot = docRoot;  
        }  
  
        public void handle(  
                final HttpRequest request,  
                final HttpResponse response,  
                final HttpContext context) throws HttpException, IOException {  
  
            String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);  
            if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {  
                throw new MethodNotSupportedException(method + " method not supported");  
            }  
            String target = request.getRequestLine().getUri();  
  
            if (request instanceof HttpEntityEnclosingRequest) {  
                HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();  
                byte[] entityContent = EntityUtils.toByteArray(entity);  
                System.out.println("Incoming entity content (bytes): " + entityContent.length);  
            }  
  
            final File file = new File(this.docRoot, URLDecoder.decode(target, "UTF-8"));  
            if (!file.exists()) {  
  
                response.setStatusCode(HttpStatus.SC_NOT_FOUND);  
                StringEntity entity = new StringEntity(  
                        "<html><body><h1>File" + file.getPath() +  
                        " not found</h1></body></html>",  
                        ContentType.create("text/html", "UTF-8"));  
                response.setEntity(entity);  
                System.out.println("File " + file.getPath() + " not found");  
  
            } else if (!file.canRead() || file.isDirectory()) {  
  
                response.setStatusCode(HttpStatus.SC_FORBIDDEN);  
                StringEntity entity = new StringEntity(  
                        "<html><body><h1>Access denied</h1></body></html>",  
                        ContentType.create("text/html", "UTF-8"));  
                response.setEntity(entity);  
                System.out.println("Cannot read file " + file.getPath());  
  
            } else {  
  
                response.setStatusCode(HttpStatus.SC_OK);  
                FileEntity body = new FileEntity(file, ContentType.create("text/html", (Charset) null));  
                response.setEntity(body);  
                System.out.println("Serving file " + file.getPath());  
            }  
        }  
  
    }  
  
    static class RequestListenerThread extends Thread {  
  
        private final ServerSocket serversocket;  
        private final HttpParams params;  
        private final HttpService httpService;  
  
        public RequestListenerThread(int port, final String docroot) throws IOException {  
            this.serversocket = new ServerSocket(port);  
            this.params = new SyncBasicHttpParams();  
            this.params  
                .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)  
                .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)  
                .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)  
                .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)  
                .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");  
  
            // Set up the HTTP protocol processor  
            HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {  
                    new ResponseDate(),  
                    new ResponseServer(),  
                    new ResponseContent(),  
                    new ResponseConnControl()  
            });  
  
            // Set up request handlers  
            HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();  
            reqistry.register("*", new HttpFileHandler(docroot));  
  
            // Set up the HTTP service  
            this.httpService = new HttpService(  
                    httpproc,  
                    new DefaultConnectionReuseStrategy(),  
                    new DefaultHttpResponseFactory(),  
                    reqistry,  
                    this.params);  
        }  
  
        @Override  
        public void run() {  
            System.out.println("Listening on port " + this.serversocket.getLocalPort());  
            while (!Thread.interrupted()) {  
                try {  
                    // Set up HTTP connection  
                    Socket socket = this.serversocket.accept();  
                    DefaultHttpServerConnection conn = new DefaultHttpServerConnection();  
                    System.out.println("Incoming connection from " + socket.getInetAddress());  
                    conn.bind(socket, this.params);  
  
                    // Start worker thread  
                    Thread t = new WorkerThread(this.httpService, conn);  
                    t.setDaemon(true);  
                    t.start();  
                } catch (InterruptedIOException ex) {  
                    break;  
                } catch (IOException e) {  
                    System.err.println("I/O error initialising connection thread: "  
                            + e.getMessage());  
                    break;  
                }  
            }  
        }  
    }  
  
    static class WorkerThread extends Thread {  
  
        private final HttpService httpservice;  
        private final HttpServerConnection conn;  
  
        public WorkerThread(  
                final HttpService httpservice,  
                final HttpServerConnection conn) {  
            super();  
            this.httpservice = httpservice;  
            this.conn = conn;  
        }  
  
        @Override  
        public void run() {  
            System.out.println("New connection thread");  
            HttpContext context = new BasicHttpContext(null);  
            try {  
                while (!Thread.interrupted() && this.conn.isOpen()) {  
                    this.httpservice.handleRequest(this.conn, context);  
                }  
            } catch (ConnectionClosedException ex) {  
                System.err.println("Client closed connection");  
            } catch (IOException ex) {  
                System.err.println("I/O error: " + ex.getMessage());  
            } catch (HttpException ex) {  
                System.err.println("Unrecoverable HTTP protocol violation: " + ex.getMessage());  
            } finally {  
                try {  
                    this.conn.shutdown();  
                } catch (IOException ignore) {}  
            }  
        }  
  
    }  
  
}  

Client case

public class ElementalHttpGet {  
  
    public static void main(String[] args) throws Exception {  
  
        HttpParams params = new SyncBasicHttpParams();  
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);  
        HttpProtocolParams.setContentCharset(params, "UTF-8");  
        HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");  
        HttpProtocolParams.setUseExpectContinue(params, true);  
  
        HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {  
                // Required protocol interceptors  
                new RequestContent(),  
                new RequestTargetHost(),  
                // Recommended protocol interceptors  
                new RequestConnControl(),  
                new RequestUserAgent(),  
                new RequestExpectContinue()});  
  
        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();  
  
        HttpContext context = new BasicHttpContext(null);  
        HttpHost host = new HttpHost("localhost", 8080);  
  
        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();  
        ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();  
  
        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);  
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);  
  
        try {  
  
            String[] targets = {  
                    "/",  
                    "/servlets-examples/servlet/RequestInfoExample",  
                    "/somewhere%20in%20pampa"};  
  
            for (int i = 0; i < targets.length; i++) {  
                if (!conn.isOpen()) {  
                    Socket socket = new Socket(host.getHostName(), host.getPort());  
                    conn.bind(socket, params);  
                }  
                BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]);  
                System.out.println(">> Request URI: " + request.getRequestLine().getUri());  
  
                request.setParams(params);  
                httpexecutor.preProcess(request, httpproc, context);  
                HttpResponse response = httpexecutor.execute(request, conn, context);  
                response.setParams(params);  
                httpexecutor.postProcess(response, httpproc, context);  
  
                System.out.println("<< Response: " + response.getStatusLine());  
                System.out.println(EntityUtils.toString(response.getEntity()));  
                System.out.println("==============");  
                if (!connStrategy.keepAlive(response, context)) {  
                    conn.close();  
                } else {  
                    System.out.println("Connection kept alive...");  
                }  
            }  
        } finally {  
            conn.close();  
        }  
    }  
  
}

public class ElementalHttpPost {  
  
    public static void main(String[] args) throws Exception {  
  
        HttpParams params = new SyncBasicHttpParams();  
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);  
        HttpProtocolParams.setContentCharset(params, "UTF-8");  
        HttpProtocolParams.setUserAgent(params, "Test/1.1");  
        HttpProtocolParams.setUseExpectContinue(params, true);  
  
        HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {  
                // Required protocol interceptors  
                new RequestContent(),  
                new RequestTargetHost(),  
                // Recommended protocol interceptors  
                new RequestConnControl(),  
                new RequestUserAgent(),  
                new RequestExpectContinue()});  
  
        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();  
  
        HttpContext context = new BasicHttpContext(null);  
  
        HttpHost host = new HttpHost("localhost", 8080);  
  
        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();  
        ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();  
  
        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);  
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);  
  
        try {  
  
            HttpEntity[] requestBodies = {  
                    new StringEntity(  
                            "This is the first test request", "UTF-8"),  
                    new ByteArrayEntity(  
                            "This is the second test request".getBytes("UTF-8")),  
                    new InputStreamEntity(  
                            new ByteArrayInputStream(  
                                    "This is the third test request (will be chunked)"  
                                    .getBytes("UTF-8")), -1)  
            };  
  
            for (int i = 0; i < requestBodies.length; i++) {  
                if (!conn.isOpen()) {  
                    Socket socket = new Socket(host.getHostName(), host.getPort());  
                    conn.bind(socket, params);  
                }  
                BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST",  
                        "/servlets-examples/servlet/RequestInfoExample");  
                request.setEntity(requestBodies[i]);  
                System.out.println(">> Request URI: " + request.getRequestLine().getUri());  
  
                request.setParams(params);  
                httpexecutor.preProcess(request, httpproc, context);  
                HttpResponse response = httpexecutor.execute(request, conn, context);  
                response.setParams(params);  
                httpexecutor.postProcess(response, httpproc, context);  
  
                System.out.println("<< Response: " + response.getStatusLine());  
                System.out.println(EntityUtils.toString(response.getEntity()));  
                System.out.println("==============");  
                if (!connStrategy.keepAlive(response, context)) {  
                    conn.close();  
                } else {  
                    System.out.println("Connection kept alive...");  
                }  
            }  
        } finally {  
            conn.close();  
        }  
    }  
  
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值