1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.jboss.as.quickstarts.jaxrsclient;
18
19
20
21
22
23
24
25
26
27 import static org.junit.Assert.*;
28
29 import java.io.BufferedReader;
30 import java.io.ByteArrayInputStream;
31 import java.io.IOException;
32 import java.io.InputStreamReader;
33
34 import javax.ws.rs.core.MediaType;
35
36 import org.apache.http.client.ClientProtocolException;
37 import org.jboss.resteasy.client.ClientRequest;
38 import org.jboss.resteasy.client.ClientResponse;
39 import org.junit.BeforeClass;
40 import org.junit.Test;
41
42
43
44
45
46
47
48 public class JaxRsClientTest {
49
50
51
52 private static String XML_URL;
53 private static String JSON_URL;
54
55
56
57
58 private static final String XML_PROPERTY = "xmlUrl";
59 private static final String JSON_PROPERTY = "jsonUrl";
60
61
62
63
64 private static final String XML_RESPONSE = "<xml><result>Hello World!</result></xml>";
65 private static final String JSON_RESPONSE = "{\"result\":\"Hello World!\"}";
66
67
68
69
70 @BeforeClass
71 public static void beforeClass() {
72 JaxRsClientTest.XML_URL = System.getProperty(JaxRsClientTest.XML_PROPERTY);
73 JaxRsClientTest.JSON_URL = System.getProperty(JaxRsClientTest.JSON_PROPERTY);
74 }
75
76
77
78
79 @Test
80 public void test() {
81 assertEquals("XML Response", JaxRsClientTest.XML_RESPONSE,
82 this.runRequest(JaxRsClientTest.XML_URL, MediaType.APPLICATION_XML_TYPE));
83
84 assertEquals("JSON Response", JaxRsClientTest.JSON_RESPONSE,
85 this.runRequest(JaxRsClientTest.JSON_URL, MediaType.APPLICATION_JSON_TYPE));
86 }
87
88
89
90
91
92
93
94 private String runRequest(String url, MediaType mediaType) {
95 String result = null;
96
97 System.out.println("===============================================");
98 System.out.println("URL: " + url);
99 System.out.println("MediaType: " + mediaType.toString());
100
101 try {
102
103
104 ClientRequest request = new ClientRequest(url);
105
106
107 request.accept(mediaType);
108
109
110 ClientResponse<String> response = request.get(String.class);
111
112
113
114 if (response.getStatus() != 200) {
115 throw new RuntimeException("Failed request with HTTP status: " + response.getStatus());
116 }
117
118
119 BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(response.getEntity()
120 .getBytes())));
121
122
123 System.out.println("\n*** Response from Server ***\n");
124 String output = null;
125 while ((output = br.readLine()) != null) {
126 System.out.println(output);
127 result = output;
128 }
129 } catch (ClientProtocolException cpe) {
130 System.err.println(cpe);
131 } catch (IOException ioe) {
132 System.err.println(ioe);
133 } catch (Exception e) {
134 System.err.println(e);
135 }
136
137 System.out.println("\n===============================================");
138
139 return result;
140 }
141
142 }