1 package ca.uhn.fhir.jpa.util;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 import org.apache.http.HttpResponse;
24 import org.apache.http.client.HttpClient;
25 import org.apache.http.client.methods.HttpDelete;
26 import org.apache.http.client.methods.HttpGet;
27 import org.apache.http.client.methods.HttpPost;
28 import org.apache.http.client.methods.HttpPut;
29 import org.apache.http.entity.StringEntity;
30 import org.apache.http.impl.client.DefaultHttpClient;
31 import org.apache.http.util.EntityUtils;
32
33 import javax.xml.ws.http.HTTPException;
34 import java.io.IOException;
35 import java.util.concurrent.TimeUnit;
36
37
38
39
40 public class RestUtilities {
41
42 public static final String CONTEXT_PATH = "";
43 public static final String APPLICATION_JSON = "application/json";
44
45
46
47
48
49
50
51
52
53 public static String getResponse(String url, MethodRequest typeRequest) throws IOException {
54 return getResponse(url, (StringEntity) null, typeRequest);
55 }
56
57
58
59
60
61
62
63
64
65
66 public static String getResponse(String url, StringEntity parameterEntity, MethodRequest typeRequest) throws IOException {
67 HttpClient httpclient = new DefaultHttpClient();
68 HttpResponse response;
69
70 switch (typeRequest) {
71 case POST:
72 HttpPost httppost = new HttpPost(url);
73 httppost.setHeader("Content-type", APPLICATION_JSON);
74 if (parameterEntity != null) {
75 httppost.setEntity(parameterEntity);
76 }
77 response = httpclient.execute(httppost);
78 break;
79 case PUT:
80 HttpPut httpPut = new HttpPut(url);
81 httpPut.setHeader("Content-type", APPLICATION_JSON);
82 if (parameterEntity != null) {
83 httpPut.setEntity(parameterEntity);
84 }
85 response = httpclient.execute(httpPut);
86 break;
87 case DELETE:
88 HttpDelete httpDelete = new HttpDelete(url);
89 httpDelete.setHeader("Content-type", APPLICATION_JSON);
90 response = httpclient.execute(httpDelete);
91 break;
92 case GET:
93 HttpGet httpGet = new HttpGet(url);
94 httpGet.setHeader("Content-type", APPLICATION_JSON);
95 response = httpclient.execute(httpGet);
96 break;
97 default:
98 throw new IllegalArgumentException("Cannot handle type request " + typeRequest);
99 }
100
101 if (response.getStatusLine().getStatusCode() < 200 || response.getStatusLine().getStatusCode() >= 300) {
102 throw new HTTPException(response.getStatusLine().getStatusCode());
103 }
104
105 if (response.getStatusLine().getStatusCode() == 204) {
106 return "";
107 }
108
109
110
111 httpclient.getConnectionManager().closeIdleConnections(1, TimeUnit.SECONDS);
112
113 return EntityUtils.toString(response.getEntity());
114 }
115 }