forked from janbodnar/Java-Advanced
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApacheHttpClientPost.java
More file actions
40 lines (28 loc) · 1.22 KB
/
ApacheHttpClientPost.java
File metadata and controls
40 lines (28 loc) · 1.22 KB
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
28
29
30
31
32
33
34
35
36
37
38
39
package com.zetcode;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
public class ApacheHttpClientPost {
public static void main(String[] args) throws IOException {
try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
HttpPost request = new HttpPost("https://httpbin.org/post");
request.setHeader("User-Agent", "Java client");
request.setEntity(new StringEntity("My test data"));
HttpResponse response = client.execute(request);
BufferedReader bufReader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
StringBuilder builder = new StringBuilder();
String line;
while ((line = bufReader.readLine()) != null) {
builder.append(line);
builder.append(System.lineSeparator());
}
System.out.println(builder);
}
}
}