2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.ci.tests.datatypes.http;
23 import org.apache.commons.io.IOUtils;
24 import org.apache.http.HttpEntity;
25 import org.apache.http.annotation.NotThreadSafe;
26 import org.apache.http.client.methods.CloseableHttpResponse;
27 import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
28 import org.apache.http.client.methods.HttpPost;
29 import org.apache.http.impl.client.CloseableHttpClient;
30 import org.apache.http.impl.client.HttpClients;
31 import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34 import sun.net.www.protocol.https.DefaultHostnameVerifier;
36 import javax.net.ssl.HostnameVerifier;
37 import javax.net.ssl.HttpsURLConnection;
39 import java.net.HttpURLConnection;
42 import java.nio.charset.Charset;
43 import java.util.List;
45 import java.util.Map.Entry;
47 public class HttpRequest {
48 static Logger logger = LoggerFactory.getLogger(HttpRequest.class.getName());
50 // -----------------------------Http------------------------------------------------------------------------
51 public RestResponse httpSendGetInternal(String url, Map<String, String> headers) throws IOException {
53 RestResponse restResponse = new RestResponse();
54 url = url.replaceAll("\\s", "%20");
55 URL obj = new URL(url);
56 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
57 // optional default is GET
58 con.setRequestMethod("GET");
59 addHttpRequestHEaders(headers, con);
61 int responseCode = con.getResponseCode();
62 logger.debug("Send GET http request, url: {}",url);
63 logger.debug("Response Code: {}",responseCode);
65 StringBuffer response = new StringBuffer();
69 result = IOUtils.toString(con.getInputStream());
70 response.append(result);
71 } catch (Exception e) {
72 logger.debug("Fail with exception", e);
75 result = IOUtils.toString(con.getErrorStream());
76 response.append(result);
77 } catch (Exception e) {
78 // logger.debug("Fail with exception", e);
81 logger.debug("Response body: {}" ,response);
84 setHttpResponseToObject(restResponse, con, responseCode, response);
90 public RestResponse httpSendByMethodInternal(String url, String method, String body, Map<String, String> headers) throws IOException {
92 RestResponse restResponse = new RestResponse();
93 URL obj = new URL(url);
94 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
96 con.setRequestMethod(method);
97 // add request headers
98 addHttpRequestHEaders(headers, con);
99 if (body != null && !body.isEmpty() && !method.equals("DELETE")) {
101 con.setDoOutput(true);
102 DataOutputStream wr = new DataOutputStream(con.getOutputStream());
108 int responseCode = con.getResponseCode();
109 logger.debug("Send {} http request, url: {}",method,url);
110 logger.debug("Response Code: {}",responseCode);
112 StringBuffer response = generateHttpResponse(con, false);
115 result = IOUtils.toString(con.getErrorStream());
116 response.append(result);
117 } catch (Exception e) {
118 // logger.debug("Fail with exception", e);
120 logger.debug("Response body: {}",response);
122 setHttpResponseToObject(restResponse, con, responseCode, response);
128 public RestResponse httpSendDelete(String url, Map<String, String> headers) throws IOException {
129 if (url.matches("^(https)://.*$")){
130 return httpsSendDelete(url, headers);
132 return httpSendDeleteInternal(url, headers);
135 public RestResponse httpSendGet(String url, Map<String, String> headers) throws IOException {
136 if (url.matches("^(https)://.*$")){
137 return httpsSendGet(url, headers);
139 return httpSendGetInternal(url, headers);
142 public RestResponse httpSendByMethod(String url, String method, String body, Map<String, String> headers) throws IOException {
143 if (url.matches("^(https)://.*$")){
144 return httpsSendByMethod(url, method, body, headers);
146 return httpSendByMethodInternal(url, method, body, headers);
149 public RestResponse httpSendPost(String url, String body, Map<String, String> headers) throws IOException {
150 if (url.matches("^(https)://.*$")){
151 return httpsSendByMethod(url, "POST", body, headers);
153 return httpSendByMethod(url, "POST", body, headers);
156 public RestResponse httpSendPut(String url, String body, Map<String, String> headers) throws IOException {
157 if (url.matches("^(https)://.*$")){
158 return httpsSendByMethod(url, "PUT", body, headers);
160 return httpSendByMethod(url, "PUT", body, headers);
164 public RestResponse httpSendDeleteInternal(String url, Map<String, String> headers) throws IOException {
166 RestResponse restResponse = new RestResponse();
167 URL obj = new URL(url);
168 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
170 addHttpRequestHEaders(headers, con);
172 con.setDoOutput(true);
173 con.setRequestMethod("DELETE");
174 int responseCode = con.getResponseCode();
175 logger.debug("Send DELETE http request, url: {}",url);
176 logger.debug("Response Code: {}",responseCode);
178 StringBuffer response = generateHttpResponse(con, false);
181 result = IOUtils.toString(con.getErrorStream());
182 response.append(result);
183 } catch (Exception e) {
184 // logger.debug("Fail with exception", e);
186 logger.debug("Response body: {}",response);
189 setHttpResponseToObject(restResponse, con, responseCode, response);
195 public static RestResponse sendHttpPostWithEntity(HttpEntity requestEntity, String url, Map<String, String> headers) throws IOException {
196 CloseableHttpResponse response = null;
197 CloseableHttpClient client = HttpClients.createDefault();
199 HttpPost httpPost = new HttpPost(url);
200 RestResponse restResponse = new RestResponse();
201 for (Entry<String, String> entry : headers.entrySet()) {
202 httpPost.addHeader(entry.getKey(), entry.getValue());
205 httpPost.setEntity(requestEntity);
206 response = client.execute(httpPost);
207 HttpEntity responseEntity = response.getEntity();
208 String responseBody = null;
209 if (responseEntity != null) {
210 InputStream instream = responseEntity.getContent();
211 StringWriter writer = new StringWriter();
212 IOUtils.copy(instream, writer);
213 responseBody = writer.toString();
221 restResponse.setErrorCode(response.getStatusLine().getStatusCode());
222 restResponse.setResponse(responseBody);
227 closeResponse(response);
228 closeHttpClient(client);
233 private static void closeHttpClient(CloseableHttpClient client) {
235 if (client != null) {
238 } catch (IOException e) {
239 logger.debug("failed to close client or response: ", e);
243 private static void closeResponse(CloseableHttpResponse response) {
245 if (response != null) {
248 } catch (IOException e) {
249 logger.debug("failed to close client or response: ", e);
254 // -----------------------------Https------------------------------------------------------------------------
255 public RestResponse httpsSendGet(String url, Map<String, String> headers) throws IOException {
257 RestResponse restResponse = new RestResponse();
258 url = url.replaceAll("\\s", "%20");
259 URL obj = new URL(null, url, new sun.net.www.protocol.https.Handler());
260 HttpsURLConnection con = (HttpsURLConnection)obj.openConnection();
261 // optional default is GET
262 con.setRequestMethod("GET");
263 HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();
264 con.setHostnameVerifier(hostnameVerifier);
265 addHttpsRequestHeaders(headers, con);
266 Boolean multiPart = false;
267 if(headers.get(HttpHeaderEnum.ACCEPT.getValue()) != null) {
268 if (headers.get(HttpHeaderEnum.ACCEPT.getValue()).equals(BaseRestUtils.acceptMultipartHeader)) {
272 int responseCode = con.getResponseCode();
273 logger.debug("Send GET http request, url: {}",url);
274 logger.debug("Response Code: {}",responseCode);
276 StringBuffer response = generateHttpsResponse(con, multiPart);
279 if(con.getErrorStream()!=null) {
280 result = IOUtils.toString(con.getErrorStream());
281 response.append(result);
283 } catch (Exception e) {
284 // logger.debug("Fail with exception", e);
286 logger.debug("Response body: {}",response);
288 setHttpsResponseToObject(restResponse, con, responseCode, response);
295 public RestResponse httpsSendPost(String url, String body, Map<String, String> headers) throws IOException {
297 RestResponse restResponse = new RestResponse();
298 URL obj = new URL(null, url, new sun.net.www.protocol.https.Handler());
299 HttpsURLConnection con = (HttpsURLConnection)obj.openConnection();
300 HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();
301 con.setHostnameVerifier(hostnameVerifier);
302 // add request method
303 con.setRequestMethod("POST");
304 // add request headers
305 addHttpRequestHEaders(headers, con);
308 con.setDoOutput(true);
309 DataOutputStream wr = new DataOutputStream(con.getOutputStream());
314 int responseCode = con.getResponseCode();
315 logger.debug("Send POST http request, url: {}",url);
316 logger.debug("Response Code: {}",responseCode);
318 StringBuffer response = generateHttpsResponse(con, false);
321 if(con.getErrorStream()!=null) {
322 result = IOUtils.toString(con.getErrorStream());
323 response.append(result);
325 } catch (Exception e) {
326 // logger.debug("Fail with exception", e);
328 logger.debug("Response body: {}",response);
330 setHttpResponseToObject(restResponse, con, responseCode, response);
336 public RestResponse httpsSendByMethod(String url, String method, String body, Map<String, String> headers) throws IOException {
338 RestResponse restResponse = new RestResponse();
339 URL obj = new URL(null, url, new sun.net.www.protocol.https.Handler());
340 HttpsURLConnection con = (HttpsURLConnection)obj.openConnection();
341 HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();
342 con.setHostnameVerifier(hostnameVerifier);
343 // add request method
344 con.setRequestMethod(method);
345 // add request headers
346 addHttpRequestHEaders(headers, con);
347 if (body != null && !body.isEmpty() && !method.equals("DELETE")) {
349 con.setDoOutput(true);
350 DataOutputStream wr = new DataOutputStream(con.getOutputStream());
356 int responseCode = con.getResponseCode();
357 logger.debug("Send {} http request, url: {}",method,url);
358 logger.debug("Response Code: {}",responseCode);
360 StringBuffer response = generateHttpResponse(con, false);
363 if(con.getErrorStream()!=null) {
364 result = IOUtils.toString(con.getErrorStream());
365 response.append(result);
367 } catch (Exception e) {
368 // logger.debug("Fail with exception", e);
370 logger.debug("Response body: {}",response);
372 setHttpResponseToObject(restResponse, con, responseCode, response);
379 public RestResponse httpsSendDelete(String url, Map<String, String> headers) throws IOException {
381 RestResponse restResponse = new RestResponse();
382 URL obj = new URL(null, url, new sun.net.www.protocol.https.Handler());
383 HttpsURLConnection con = (HttpsURLConnection)obj.openConnection();
384 HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();
385 con.setHostnameVerifier(hostnameVerifier);
386 // add request headers
387 addHttpRequestHEaders(headers, con);
389 con.setDoOutput(true);
390 con.setRequestMethod("DELETE");
391 int responseCode = con.getResponseCode();
392 logger.debug("Send DELETE http request, url: {}",url);
393 logger.debug("Response Code: {}",responseCode);
395 StringBuffer response = generateHttpsResponse(con, false);
398 if(con.getErrorStream()!=null) {
399 result = IOUtils.toString(con.getErrorStream());
400 response.append(result);
402 } catch (Exception e) {
403 // logger.debug("Fail with exception", e);
405 logger.debug("Response body: {}",response);
407 setHttpResponseToObject(restResponse, con, responseCode, response);
413 // ---------------------------------------
414 private void addHttpsRequestHeaders(Map<String, String> headers, HttpsURLConnection con) {
415 // add request header
416 if (headers != null) {
417 for (Entry<String, String> header : headers.entrySet()) {
418 String key = header.getKey();
419 String value = header.getValue();
420 con.setRequestProperty(key, value);
426 private void addHttpRequestHEaders(Map<String, String> headers, HttpURLConnection con) {
427 // add request header
428 if (headers != null) {
429 for (Entry<String, String> header : headers.entrySet()) {
430 String key = header.getKey();
431 String value = header.getValue();
432 con.setRequestProperty(key, value);
438 private void setHttpResponseToObject(RestResponse restResponse, HttpURLConnection con, int responseCode, StringBuffer response) throws IOException {
439 restResponse.setErrorCode(responseCode);
441 if (response != null) {
442 restResponse.setResponse(response.toString());
445 Map<String, List<String>> headerFields = con.getHeaderFields();
446 restResponse.setHeaderFields(headerFields);
447 String responseMessage = con.getResponseMessage();
448 restResponse.setResponseMessage(responseMessage);
451 private StringBuffer generateHttpResponse(HttpURLConnection con, Boolean isMultiPart) {
452 StringBuffer response = new StringBuffer();
453 StringWriter writer = new StringWriter();
456 IOUtils.copy((con.getInputStream()), writer, Charset.forName("UTF-8"));
457 response = writer.getBuffer();
460 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
462 while ((inputLine = in.readLine()) != null) {
463 response.append(inputLine);
467 } catch (Exception e) {
468 logger.debug("response body is null");
474 private void setHttpsResponseToObject(RestResponse restResponse, HttpsURLConnection con, int responseCode, StringBuffer response) throws IOException {
475 if (response != null) {
476 restResponse.setResponse(response.toString());
479 restResponse.setErrorCode(responseCode);
480 // restResponse.setResponse(result);
481 Map<String, List<String>> headerFields = con.getHeaderFields();
482 restResponse.setHeaderFields(headerFields);
483 String responseMessage = con.getResponseMessage();
484 restResponse.setResponseMessage(responseMessage);
487 private StringBuffer generateHttpsResponse(HttpsURLConnection con, Boolean isMultiPart) {
488 StringBuffer response = new StringBuffer();
489 StringWriter writer = new StringWriter();
492 IOUtils.copy((con.getInputStream()), writer, Charset.forName("UTF-8"));
493 response = writer.getBuffer();
496 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
498 while ((inputLine = in.readLine()) != null) {
499 response.append(inputLine);
503 } catch (Exception e) {
504 logger.debug("response body is null");
512 class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
513 public static final String METHOD_NAME = "DELETE";
515 public String getMethod() {
519 public HttpDeleteWithBody(final String uri) {
521 setURI(URI.create(uri));
524 public HttpDeleteWithBody(final URI uri) {
529 public HttpDeleteWithBody() {