|
| 1 | +package Http; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +import org.apache.http.HttpEntity; |
| 7 | +import org.apache.http.NameValuePair; |
| 8 | +import org.apache.http.client.entity.UrlEncodedFormEntity; |
| 9 | +import org.apache.http.client.methods.CloseableHttpResponse; |
| 10 | +import org.apache.http.client.methods.HttpGet; |
| 11 | +import org.apache.http.client.methods.HttpPost; |
| 12 | +import org.apache.http.impl.client.CloseableHttpClient; |
| 13 | +import org.apache.http.impl.client.HttpClients; |
| 14 | +import org.apache.http.message.BasicNameValuePair; |
| 15 | +import org.apache.http.util.EntityUtils; |
| 16 | + |
| 17 | +public class HttpClientTest { |
| 18 | + |
| 19 | + public static void main(String[] args) throws Exception { |
| 20 | + CloseableHttpClient httpclient = HttpClients.createDefault(); |
| 21 | + try { |
| 22 | + HttpGet httpGet = new HttpGet("http://httpbin.org/get"); |
| 23 | + CloseableHttpResponse response1 = httpclient.execute(httpGet); |
| 24 | + // The underlying HTTP connection is still held by the response object |
| 25 | + // to allow the response content to be streamed directly from the network socket. |
| 26 | + // In order to ensure correct deallocation of system resources |
| 27 | + // the user MUST call CloseableHttpResponse#close() from a finally clause. |
| 28 | + // Please note that if response content is not fully consumed the underlying |
| 29 | + // connection cannot be safely re-used and will be shut down and discarded |
| 30 | + // by the connection manager. |
| 31 | + try { |
| 32 | + System.out.println(response1.getStatusLine()); |
| 33 | + HttpEntity entity1 = response1.getEntity(); |
| 34 | + // do something useful with the response body |
| 35 | + // and ensure it is fully consumed |
| 36 | + EntityUtils.consume(entity1); |
| 37 | + } finally { |
| 38 | + response1.close(); |
| 39 | + } |
| 40 | + |
| 41 | + HttpPost httpPost = new HttpPost("http://httpbin.org/post"); |
| 42 | + List <NameValuePair> nvps = new ArrayList <NameValuePair>(); |
| 43 | + nvps.add(new BasicNameValuePair("username", "vip")); |
| 44 | + nvps.add(new BasicNameValuePair("password", "secret")); |
| 45 | + httpPost.setEntity(new UrlEncodedFormEntity(nvps)); |
| 46 | + CloseableHttpResponse response2 = httpclient.execute(httpPost); |
| 47 | + |
| 48 | + try { |
| 49 | + System.out.println(response2.getStatusLine()); |
| 50 | + HttpEntity entity2 = response2.getEntity(); |
| 51 | + // do something useful with the response body |
| 52 | + // and ensure it is fully consumed |
| 53 | + EntityUtils.consume(entity2); |
| 54 | + } finally { |
| 55 | + response2.close(); |
| 56 | + } |
| 57 | + } finally { |
| 58 | + httpclient.close(); |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | +} |
0 commit comments