1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 package org.apache.hc.client5.http.examples;
28
29 import java.util.ArrayList;
30 import java.util.List;
31
32 import org.apache.hc.client5.http.classic.methods.HttpGet;
33 import org.apache.hc.client5.http.classic.methods.HttpPost;
34 import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
35 import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
36 import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
37 import org.apache.hc.client5.http.impl.classic.HttpClients;
38 import org.apache.hc.core5.http.HttpEntity;
39 import org.apache.hc.core5.http.NameValuePair;
40 import org.apache.hc.core5.http.io.entity.EntityUtils;
41 import org.apache.hc.core5.http.message.BasicNameValuePair;
42
43 public class QuickStart {
44
45 public static void main(final String[] args) throws Exception {
46 try (final CloseableHttpClient httpclient = HttpClients.createDefault()) {
47 final HttpGet httpGet = new HttpGet("http://httpbin.org/get");
48
49
50
51
52
53
54
55 try (final CloseableHttpResponse response1 = httpclient.execute(httpGet)) {
56 System.out.println(response1.getCode() + " " + response1.getReasonPhrase());
57 final HttpEntity entity1 = response1.getEntity();
58
59
60 EntityUtils.consume(entity1);
61 }
62
63 final HttpPost httpPost = new HttpPost("http://httpbin.org/post");
64 final List<NameValuePair> nvps = new ArrayList<>();
65 nvps.add(new BasicNameValuePair("username", "vip"));
66 nvps.add(new BasicNameValuePair("password", "secret"));
67 httpPost.setEntity(new UrlEncodedFormEntity(nvps));
68
69 try (final CloseableHttpResponse response2 = httpclient.execute(httpPost)) {
70 System.out.println(response2.getCode() + " " + response2.getReasonPhrase());
71 final HttpEntity entity2 = response2.getEntity();
72
73
74 EntityUtils.consume(entity2);
75 }
76 }
77 }
78
79 }