使用阻塞型HTTP连接

HttpCore不对建立连接提供完全支持,因为建立新连接的过程,尤其对于客户端,在包括一次或多次认证或通道代理时可能会很复杂。阻塞型HTTP连接可以建立在任意网络套接字上。

Socket socket = <...>
DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024);
conn.bind(socket);
System.out.println(conn.isOpen());
HttpConnectionMetrics metrics = conn.getMetrics();
System.out.println(metrics.getRequestCount());
System.out.println(metrics.getResponseCount());
System.out.println(metrics.getReceivedBytesCount());
System.out.println(metrics.getSentBytesCount());

客户端和服务器端的HTTP连接接口,通过两步发送和接受报文。首先报文头被发出。根据报文头的属性,报文体随后发出。注意,关闭内容数据流是非常重要的,表示报文处理已经完成。从输入流连接直接输出的HTTP实体必须保证报文内容完全被读取,这样连接才可能被复用。

一个简化的客户端请求执行过程:

Socket socket = <...>
DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024);
conn.bind(socket);
HttpRequest request = new BasicHttpRequest("GET", "/");
conn.sendRequestHeader(request);
HttpResponse response = conn.receiveResponseHeader();
conn.receiveResponseEntity(response);
HttpEntity entity = response.getEntity();
if (entity != null) {
    // Do something useful with the entity and, when done, ensure all
    // content has been consumed, so that the underlying connection
    // can be re-used
    EntityUtils.consume(entity);
}

一个简化的服务器端处理请求的过程:

Socket socket = <...>


DefaultBHttpServerConnection conn = new DefaultBHttpServerConnection(8 * 1024);
conn.bind(socket);
HttpRequest request = conn.receiveRequestHeader();
if (request instanceof HttpEntityEnclosingRequest) {
    conn.receiveRequestEntity((HttpEntityEnclosingRequest) request);
    HttpEntity entity = ((HttpEntityEnclosingRequest) request)
            .getEntity();
    if (entity != null) {
        // Do something useful with the entity and, when done, ensure all
        // content has been consumed, so that the underlying connection
        // could be re-used
        EntityUtils.consume(entity);
    }
}
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK") ;
response.setEntity(new StringEntity("Got it") );
conn.sendResponseHeader(response);
conn.sendResponseEntity(response);

注意,通常不需要使用这些底层方法,只需要使用合适的高层的HTTP服务即可。

results matching ""

    No results matching ""