Created
November 26, 2013 18:58
-
-
Save bennettandrews/7663829 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.apache.http.examples.client; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import org.apache.http.HttpEntity; | |
import org.apache.http.client.methods.CloseableHttpResponse; | |
import org.apache.http.client.methods.HttpGet; | |
import org.apache.http.impl.client.CloseableHttpClient; | |
import org.apache.http.impl.client.HttpClients; | |
/** | |
* 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 { | |
CloseableHttpClient httpclient = HttpClients.createDefault(); | |
try { | |
HttpGet httpget = new HttpGet("http://www.apache.org/"); | |
// Execute HTTP request | |
System.out.println("executing request " + httpget.getURI()); | |
CloseableHttpResponse response = httpclient.execute(httpget); | |
try { | |
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) { | |
InputStream instream = entity.getContent(); | |
try { | |
instream.read(); | |
// do something useful with the response | |
} catch (IOException ex) { | |
// In case of an IOException the connection will be released | |
// back to the connection manager automatically | |
throw ex; | |
} finally { | |
// Closing the input stream will trigger connection release | |
instream.close(); | |
} | |
} | |
} finally { | |
response.close(); | |
} | |
} finally { | |
httpclient.close(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment