Skip to content

Commit 54538e9

Browse files
committed
add Java RESTFul client examples
1 parent d966f08 commit 54538e9

File tree

10 files changed

+377
-0
lines changed

10 files changed

+377
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<classpath>
3+
<classpathentry kind="src" output="target/classes" path="src/main/java">
4+
<attributes>
5+
<attribute name="optional" value="true"/>
6+
<attribute name="maven.pomderived" value="true"/>
7+
</attributes>
8+
</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>
14+
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
15+
<attributes>
16+
<attribute name="optional" value="true"/>
17+
<attribute name="maven.pomderived" value="true"/>
18+
</attributes>
19+
</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>
25+
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
26+
<attributes>
27+
<attribute name="maven.pomderived" value="true"/>
28+
</attributes>
29+
</classpathentry>
30+
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
31+
<attributes>
32+
<attribute name="maven.pomderived" value="true"/>
33+
</attributes>
34+
</classpathentry>
35+
<classpathentry kind="output" path="target/classes"/>
36+
</classpath>
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
/target/
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
eclipse.preferences.version=1
2+
encoding//src/main/java=UTF-8
3+
encoding//src/main/resources=UTF-8
4+
encoding//src/test/java=UTF-8
5+
encoding//src/test/resources=UTF-8
6+
encoding/<project>=UTF-8
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
eclipse.preferences.version=1
2+
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
3+
org.eclipse.jdt.core.compiler.compliance=1.8
4+
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
5+
org.eclipse.jdt.core.compiler.source=1.8
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
activeProfiles=
2+
eclipse.preferences.version=1
3+
resolveWorkspaceProjects=true
4+
version=1
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<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>
12+
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+
</dependencies>
25+
</project>
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.howtoprogram.restful;
2+
3+
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
4+
5+
@JacksonXmlRootElement(localName = "book")
6+
public class Book {
7+
8+
private Long id;
9+
private String name;
10+
private String author;
11+
12+
13+
public Book() {
14+
super();
15+
}
16+
17+
public Book(Long id, String name, String author) {
18+
super();
19+
this.id = id;
20+
this.name = name;
21+
this.author = author;
22+
}
23+
24+
@Override
25+
public String toString() {
26+
return "Book [id=" + id + ", name=" + name + ", author=" + author + "]";
27+
}
28+
29+
30+
}
Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
package com.howtoprogram.restful;
2+
3+
import java.io.BufferedReader;
4+
import java.io.IOException;
5+
import java.io.InputStreamReader;
6+
import java.io.OutputStream;
7+
import java.net.HttpURLConnection;
8+
import java.net.URL;
9+
10+
import com.fasterxml.jackson.databind.ObjectMapper;
11+
import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule;
12+
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
13+
14+
public class BookServiceImplJackson {
15+
16+
17+
/**
18+
* Gets all {@link Book} from RESTful Web Service; then, use Jackson library to convert the JSON
19+
* response to Java objects
20+
*/
21+
public void getAllBooksAsJson() {
22+
HttpURLConnection connection = null;
23+
BufferedReader reader = null;
24+
String json = null;
25+
try {
26+
URL resetEndpoint = new URL("http://localhost:8080/v1/books");
27+
connection = (HttpURLConnection) resetEndpoint.openConnection();
28+
// Set request method to GET as required from the API
29+
connection.setRequestMethod("GET");
30+
31+
// Read the response
32+
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
33+
StringBuilder jsonSb = new StringBuilder();
34+
String line = null;
35+
while ((line = reader.readLine()) != null) {
36+
jsonSb.append(line);
37+
}
38+
json = jsonSb.toString();
39+
40+
// Converts JSON string to Java object
41+
ObjectMapper mapper = new ObjectMapper();
42+
// Converts to an array of Book
43+
Book[] books = mapper.readValue(json, Book[].class);
44+
for (Book book : books) {
45+
System.out.println(book);
46+
}
47+
} catch (Exception e) {
48+
e.printStackTrace();
49+
}
50+
}
51+
52+
/**
53+
* Creates {@link Book} by posting the XML to RESTful Web Service. The XML content is converted
54+
* from Java object using Jackson API
55+
*/
56+
57+
public void createBookAsXML() {
58+
try {
59+
URL url = new URL("http://localhost:8080/v1/books");
60+
HttpURLConnection con = (HttpURLConnection) url.openConnection();
61+
// Set the request method to POST as required from the API
62+
con.setRequestMethod("POST");
63+
64+
// Set the Content-Type to "application/xml" as required from the API
65+
con.setRequestProperty("Content-Type", "application/xml");
66+
con.setDoOutput(true);
67+
68+
OutputStream os = con.getOutputStream();
69+
// The book we want to create in JSON format
70+
// String book = "<book><name>Effective Java</name><author>Joshua Bloch</author></book>";
71+
// Creates new Book instance
72+
Book book = new Book(null, "Effective Java", "Joshua Bloch");
73+
JacksonXmlModule module = new JacksonXmlModule();
74+
// and then configure, for example:
75+
module.setDefaultUseWrapper(false);
76+
XmlMapper xmlMapper = new XmlMapper(module);
77+
System.out.println(xmlMapper.writeValueAsString(book));
78+
79+
os.write(xmlMapper.writeValueAsBytes(book));
80+
os.flush();
81+
os.close();
82+
83+
int responseCode = con.getResponseCode();
84+
85+
System.out.println("Response Code :" + responseCode);
86+
87+
if (responseCode == HttpURLConnection.HTTP_CREATED) {
88+
System.out.println("Created book successfully.");
89+
} else {
90+
System.out.println("Created book failed.");
91+
}
92+
} catch (Exception e) {
93+
e.printStackTrace();
94+
}
95+
96+
}
97+
98+
99+
/**
100+
* Creates {@link Book} by posting the JSON to RESTful Web Service. The JSON content is converted
101+
* from Java object using Jackson API
102+
*/
103+
104+
public void createBookAsJSON() {
105+
try {
106+
URL url = new URL("http://localhost:8080/v1/books");
107+
HttpURLConnection con = (HttpURLConnection) url.openConnection();
108+
// Set the request method to POST as required from the API
109+
con.setRequestMethod("POST");
110+
111+
// Set the Content-Type to "application/json" as required from the API
112+
con.setRequestProperty("Content-Type", "application/json");
113+
con.setDoOutput(true);
114+
115+
OutputStream os = con.getOutputStream();
116+
// The book we want to create in JSON format
117+
// String book = "{\"name\":\"Effective Java\",\"author\":\"Joshua Bloch\"}";
118+
// Creates new Book instance
119+
Book book = new Book(null, "Effective Java", "Joshua Bloch");
120+
ObjectMapper mapper = new ObjectMapper();
121+
os.write(mapper.writeValueAsBytes(book));
122+
os.flush();
123+
os.close();
124+
125+
int responseCode = con.getResponseCode();
126+
127+
System.out.println("Response Code :" + responseCode);
128+
129+
if (responseCode == HttpURLConnection.HTTP_CREATED) {
130+
System.out.println("Created book successfully.");
131+
} else {
132+
System.out.println("Created book failed.");
133+
}
134+
} catch (Exception e) {
135+
e.printStackTrace();
136+
}
137+
138+
}
139+
140+
141+
}
Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
package com.howtoprogram.restful;
2+
3+
import java.io.BufferedReader;
4+
import java.io.IOException;
5+
import java.io.InputStreamReader;
6+
import java.io.OutputStream;
7+
import java.net.HttpURLConnection;
8+
import java.net.URL;
9+
10+
public class BookServiceImplRaw {
11+
12+
/**
13+
* Get all {@link Book} from RESTful Web Service
14+
*/
15+
public String getAllBooksAsJson() {
16+
HttpURLConnection connection = null;
17+
BufferedReader reader = null;
18+
String retVal = null;
19+
try {
20+
URL resetEndpoint = new URL("http://localhost:8080/v1/books");
21+
connection = (HttpURLConnection) resetEndpoint.openConnection();
22+
// Set request method to GET as required from the API
23+
connection.setRequestMethod("GET");
24+
25+
// Read the response
26+
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
27+
StringBuilder jsonSb = new StringBuilder();
28+
String line = null;
29+
while ((line = reader.readLine()) != null) {
30+
jsonSb.append(line);
31+
}
32+
retVal = jsonSb.toString();
33+
34+
// print out the json response
35+
System.out.println(retVal);
36+
37+
} catch (Exception e) {
38+
e.printStackTrace();
39+
} finally {
40+
// Clean up
41+
if (reader != null) {
42+
try {
43+
reader.close();
44+
} catch (IOException e) {
45+
e.printStackTrace();
46+
}
47+
}
48+
if (connection != null) {
49+
connection.disconnect();
50+
}
51+
}
52+
return retVal;
53+
}
54+
55+
56+
/**
57+
* Creates {@link Book} by posting the XML to RESTful Web Service
58+
*/
59+
public void createBookAsXML() {
60+
try {
61+
URL url = new URL("http://localhost:8080/v1/books");
62+
HttpURLConnection con = (HttpURLConnection) url.openConnection();
63+
// Set the request method to POST as required from the API
64+
con.setRequestMethod("POST");
65+
66+
// Set the Content-Type to "application/xml" as required from the API
67+
con.setRequestProperty("Content-Type", "application/xml");
68+
con.setDoOutput(true);
69+
70+
OutputStream os = con.getOutputStream();
71+
// The book we want to create in JSON format
72+
String book = "<book><name>Effective Java</name><author>Joshua Bloch</author></book>";
73+
os.write(book.getBytes());
74+
os.flush();
75+
os.close();
76+
77+
int responseCode = con.getResponseCode();
78+
79+
System.out.println("Response Code :" + responseCode);
80+
81+
if (responseCode == HttpURLConnection.HTTP_CREATED) {
82+
System.out.println("Created book successfully.");
83+
} else {
84+
System.out.println("Created book failed.");
85+
}
86+
} catch (Exception e) {
87+
e.printStackTrace();
88+
}
89+
90+
}
91+
92+
/**
93+
* Creates {@link Book} by posting the JSON to RESTful Web Service
94+
*/
95+
public void createBookAsJSON() {
96+
try {
97+
URL url = new URL("http://localhost:8080/v1/books");
98+
HttpURLConnection con = (HttpURLConnection) url.openConnection();
99+
// Set the request method to POST as required from the API
100+
con.setRequestMethod("POST");
101+
102+
// Set the Content-Type to "application/json" as required from the API
103+
con.setRequestProperty("Content-Type", "application/json");
104+
con.setDoOutput(true);
105+
106+
OutputStream os = con.getOutputStream();
107+
// The book we want to create in JSON format
108+
String book = "{\"name\":\"Effective Java\",\"author\":\"Joshua Bloch\"}";
109+
os.write(book.getBytes());
110+
os.flush();
111+
os.close();
112+
113+
int responseCode = con.getResponseCode();
114+
115+
System.out.println("Response Code :" + responseCode);
116+
117+
if (responseCode == HttpURLConnection.HTTP_CREATED) {
118+
System.out.println("Created book successfully.");
119+
} else {
120+
System.out.println("Created book failed.");
121+
}
122+
} catch (Exception e) {
123+
e.printStackTrace();
124+
}
125+
}
126+
127+
128+
129+
}

0 commit comments

Comments
 (0)