HttpClient Examples:Manual connection release

官方主頁:http://hc.apache.org/

 

Components
  • Manual connection release

    This example demonstrates how to ensure the release of the underlying HTTP connection back to the connection manager in case of a manual processing of HTTP responses.

  •  

    这个例子示范了如何确保释放基本的HTTP连接回到连接管理器的情况下人工处理HTTP响应。

     

    package cn.lake.util;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.DefaultHttpClient;
    
    /**
     * This example demonstrates the recommended way of using API to make sure the
     * underlying connection gets released back to the connection manager.
     */
    public class ClientConnectionRelease {
    
    	public final static void main(String[] args) throws Exception {
    		HttpClient httpclient = new DefaultHttpClient();
    
    		HttpGet httpget = new HttpGet("http://www.apache.org/");
    
    		// Execute HTTP request
    		System.out.println("executing request " + httpget.getURI());
    		HttpResponse response = httpclient.execute(httpget);
    
    		System.out.println("----------------------------------------");
    		System.out.println(response.getStatusLine());
    		System.out.println("----------------------------------------");
    
    		// Get hold of the response entity
    		HttpEntity entity = response.getEntity();
    
    		// If the response does not enclose an entity, there is no need
    		// to bother about connection release
    		if (entity != null) {
    			BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
    			try {
    
    				// do something useful with the response
    				System.out.println(reader.readLine());
    
    			} catch (IOException ex) {
    
    				// In case of an IOException the connection will be released
    				// back to the connection manager automatically
    				throw ex;
    
    			} catch (RuntimeException ex) {
    
    				// In case of an unexpected exception you may want to abort
    				// the HTTP request in order to shut down the underlying
    				// connection and release it back to the connection manager.
    				httpget.abort();
    				throw ex;
    
    			} finally {
    
    				// Closing the input stream will trigger connection release
    				reader.close();
    
    			}
    		}
    	}
    
    }
    

     

     

    也是一个GET请求的实例,因为里面reader.readLine(),只读了一行,所以显示只是第一行会被打印出来,如果加一个while循环就可以把整个页面打印出来!

     

    翻譯的不好,請見諒!

     

     

    你可能感兴趣的:(apache)