Skip to content

Commit ed67699

Browse files
committed
ApacheHttp client
1 parent 9b1cc2c commit ed67699

File tree

6 files changed

+222
-38
lines changed

6 files changed

+222
-38
lines changed

Java-RESTful-Client-Example/.classpath

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,22 +6,12 @@
66
<attribute name="maven.pomderived" value="true"/>
77
</attributes>
88
</classpathentry>
9-
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
10-
<attributes>
11-
<attribute name="maven.pomderived" value="true"/>
12-
</attributes>
13-
</classpathentry>
149
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
1510
<attributes>
1611
<attribute name="optional" value="true"/>
1712
<attribute name="maven.pomderived" value="true"/>
1813
</attributes>
1914
</classpathentry>
20-
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
21-
<attributes>
22-
<attribute name="maven.pomderived" value="true"/>
23-
</attributes>
24-
</classpathentry>
2515
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
2616
<attributes>
2717
<attribute name="maven.pomderived" value="true"/>

Java-RESTful-Client-Example/.project

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,14 @@
1515
<arguments>
1616
</arguments>
1717
</buildCommand>
18+
<buildCommand>
19+
<name>org.springframework.ide.eclipse.core.springbuilder</name>
20+
<arguments>
21+
</arguments>
22+
</buildCommand>
1823
</buildSpec>
1924
<natures>
25+
<nature>org.springframework.ide.eclipse.core.springnature</nature>
2026
<nature>org.eclipse.jdt.core.javanature</nature>
2127
<nature>org.eclipse.m2e.core.maven2Nature</nature>
2228
</natures>
Lines changed: 47 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,50 @@
11
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2-
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3-
<modelVersion>4.0.0</modelVersion>
4-
<groupId>com.howtoprogram</groupId>
5-
<artifactId>java-restful-client-example</artifactId>
6-
<version>0.0.1-SNAPSHOT</version>
7-
<properties>
8-
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
9-
<maven.compiler.source>1.8</maven.compiler.source>
10-
<maven.compiler.target>1.8</maven.compiler.target>
11-
</properties>
2+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3+
<modelVersion>4.0.0</modelVersion>
4+
<groupId>com.howtoprogram</groupId>
5+
<artifactId>java-restful-client-example</artifactId>
6+
<version>0.0.1-SNAPSHOT</version>
7+
<properties>
8+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
9+
<maven.compiler.source>1.8</maven.compiler.source>
10+
<maven.compiler.target>1.8</maven.compiler.target>
11+
</properties>
1212

13-
<dependencies>
14-
<dependency>
15-
<groupId>com.fasterxml.jackson.core</groupId>
16-
<artifactId>jackson-databind</artifactId>
17-
<version>2.7.5</version>
18-
</dependency>
19-
<dependency>
20-
<groupId>com.fasterxml.jackson.dataformat</groupId>
21-
<artifactId>jackson-dataformat-xml</artifactId>
22-
<version>2.6.3</version>
23-
</dependency>
24-
<dependency>
25-
<groupId>org.springframework</groupId>
26-
<artifactId>spring-web</artifactId>
27-
<version>4.2.6.RELEASE</version>
28-
</dependency>
29-
</dependencies>
13+
<dependencies>
14+
<dependency>
15+
<groupId>com.fasterxml.jackson.core</groupId>
16+
<artifactId>jackson-databind</artifactId>
17+
<version>2.7.5</version>
18+
</dependency>
19+
<dependency>
20+
<groupId>com.fasterxml.jackson.dataformat</groupId>
21+
<artifactId>jackson-dataformat-xml</artifactId>
22+
<version>2.6.3</version>
23+
</dependency>
24+
<dependency>
25+
<groupId>org.springframework</groupId>
26+
<artifactId>spring-web</artifactId>
27+
<version>4.2.6.RELEASE</version>
28+
</dependency>
29+
<dependency>
30+
<groupId>org.apache.httpcomponents</groupId>
31+
<artifactId>httpclient</artifactId>
32+
<version>4.5.2</version>
33+
</dependency>
34+
<dependency>
35+
<groupId>org.apache.httpcomponents</groupId>
36+
<artifactId>httpasyncclient</artifactId>
37+
<version>4.1.2</version>
38+
</dependency>
39+
<dependency>
40+
<groupId>org.slf4j</groupId>
41+
<artifactId>slf4j-api</artifactId>
42+
<version>1.7.21</version>
43+
</dependency>
44+
<dependency>
45+
<groupId>ch.qos.logback</groupId>
46+
<artifactId>logback-classic</artifactId>
47+
<version>1.1.7</version>
48+
</dependency>
49+
</dependencies>
3050
</project>

Java-RESTful-Client-Example/src/main/java/com/howtoprogram/restful/BookRepositoryImplJackson.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package com.howtoprogram.restful;
22

33
import java.io.BufferedReader;
4-
import java.io.IOException;
54
import java.io.InputStreamReader;
65
import java.io.OutputStream;
76
import java.net.HttpURLConnection;
Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
package com.howtoprogram.service;
2+
3+
import java.util.concurrent.Future;
4+
5+
import org.apache.http.HttpEntity;
6+
import org.apache.http.HttpResponse;
7+
import org.apache.http.HttpStatus;
8+
import org.apache.http.client.methods.HttpDelete;
9+
import org.apache.http.client.methods.HttpGet;
10+
import org.apache.http.client.methods.HttpPost;
11+
import org.apache.http.client.methods.HttpPut;
12+
import org.apache.http.entity.StringEntity;
13+
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
14+
import org.apache.http.impl.nio.client.HttpAsyncClients;
15+
import org.apache.http.nio.client.util.HttpAsyncClientUtils;
16+
17+
import com.fasterxml.jackson.databind.ObjectMapper;
18+
import com.howtoprogram.domain.Book;
19+
20+
public class BookRepositoryImplApacheHttpClient {
21+
private static final String URI_BOOK = "http://localhost:8080/v1/books";
22+
23+
public boolean deleteBook(Long id) {
24+
boolean retVal = false;
25+
CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
26+
try {
27+
httpclient.start();
28+
// Create a delete method instance.
29+
HttpDelete request = new HttpDelete(URI_BOOK + "/" + id);
30+
Future<HttpResponse> future = httpclient.execute(request, null);
31+
// Wait and retrieve the result
32+
HttpResponse response = future.get();
33+
System.out.println("Response code:" + response.getStatusLine().getStatusCode());
34+
// Determine whether the request was successfully or not
35+
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
36+
retVal = true;
37+
}
38+
} catch (Exception e) {
39+
e.printStackTrace();
40+
} finally {
41+
HttpAsyncClientUtils.closeQuietly(httpclient);
42+
}
43+
return retVal;
44+
}
45+
46+
public Book updateBook(Book book) {
47+
48+
CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
49+
Book createdBook = null;
50+
try {
51+
httpclient.start();
52+
// Create a HttpPut instance.
53+
HttpPut request = new HttpPut(URI_BOOK + "/" + book.getId());
54+
// Create new instance of ObjectMapper
55+
ObjectMapper mapper = new ObjectMapper();
56+
String jsonBook = mapper.writeValueAsString(book);
57+
StringEntity entity = new StringEntity(jsonBook);
58+
// Set the entity for the request
59+
request.setEntity(entity);
60+
61+
Future<HttpResponse> future = httpclient.execute(request, null);
62+
// Wait and retrieve the result
63+
HttpResponse response = future.get();
64+
System.out.println("Response code:" + response.getStatusLine().getStatusCode());
65+
// Determine whether the request was successfully or not
66+
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
67+
// Get back the updated book
68+
createdBook = mapper.readValue(response.getEntity().getContent(), Book.class);
69+
70+
}
71+
} catch (Exception e) {
72+
e.printStackTrace();
73+
} finally {
74+
HttpAsyncClientUtils.closeQuietly(httpclient);
75+
}
76+
return createdBook;
77+
78+
}
79+
80+
public Book createBook(Book book) {
81+
82+
CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
83+
Book createdBook = null;
84+
try {
85+
httpclient.start();
86+
// Create a delete method instance.
87+
HttpPost request = new HttpPost(URI_BOOK);
88+
// Create new instance of ObjectMapper
89+
ObjectMapper mapper = new ObjectMapper();
90+
String jsonBook = mapper.writeValueAsString(book);
91+
StringEntity entity = new StringEntity(jsonBook);
92+
// Set the entity for the request
93+
request.setEntity(entity);
94+
95+
Future<HttpResponse> future = httpclient.execute(request, null);
96+
// Wait and retrieve the result
97+
HttpResponse response = future.get();
98+
System.out.println("Response code:" + response.getStatusLine().getStatusCode());
99+
// Determine whether the request was successfully or not
100+
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
101+
// Get back the created book
102+
createdBook = mapper.readValue(response.getEntity().getContent(), Book.class);
103+
104+
}
105+
} catch (Exception e) {
106+
e.printStackTrace();
107+
} finally {
108+
HttpAsyncClientUtils.closeQuietly(httpclient);
109+
}
110+
return createdBook;
111+
112+
}
113+
114+
public static void main(String[] args) {
115+
BookRepositoryImplApacheHttpClient repository = new BookRepositoryImplApacheHttpClient();
116+
// Getting the first book from the RESTful service
117+
Book book = repository.getAllBooks()[0];
118+
System.out.println(book);
119+
120+
}
121+
122+
123+
public Book[] getAllBooks() {
124+
125+
Book[] books = null;
126+
// Create an asyn HttpClient
127+
CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
128+
try {
129+
httpclient.start();
130+
HttpGet request = new HttpGet(URI_BOOK);
131+
Future<HttpResponse> future = httpclient.execute(request, null);
132+
// Wait and retrieve the result
133+
HttpResponse response = future.get();
134+
System.out.println("Response code:" + response.getStatusLine().getStatusCode());
135+
// Determine whether the request was successfully or not
136+
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
137+
HttpEntity httpEntity = response.getEntity();
138+
// Create a Jackson ObjectMapper to convert the JSON response to Java objects
139+
ObjectMapper mapper = new ObjectMapper();
140+
// Read the inputstream and convert to an array of Book
141+
books = mapper.readValue(httpEntity.getContent(), Book[].class);
142+
}
143+
} catch (Exception ex) {
144+
ex.printStackTrace();
145+
} finally {
146+
HttpAsyncClientUtils.closeQuietly(httpclient);
147+
}
148+
return books;
149+
}
150+
151+
public Book findBookById(Long id) {
152+
return null;
153+
}
154+
155+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<configuration>
2+
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
3+
<encoder>
4+
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
5+
</pattern>
6+
</encoder>
7+
</appender>
8+
9+
<logger name="deng" level="DEBUG" />
10+
11+
<root level="DEBUG">
12+
<appender-ref ref="STDOUT" />
13+
</root>
14+
</configuration>

0 commit comments

Comments
 (0)