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.ClientProtocolException;
27 import org.apache.http.client.methods.CloseableHttpResponse;
28 import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
29 import org.apache.http.client.methods.HttpPost;
30 import org.apache.http.impl.client.CloseableHttpClient;
31 import org.apache.http.impl.client.HttpClients;
32 import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35 import sun.net.www.protocol.https.DefaultHostnameVerifier;
37 import javax.net.ssl.HostnameVerifier;
38 import javax.net.ssl.HttpsURLConnection;
40 import java.net.HttpURLConnection;
43 import java.nio.charset.Charset;
44 import java.util.List;
46 import java.util.Map.Entry;
48 public class HttpRequest {
49 static Logger logger = LoggerFactory.getLogger(HttpRequest.class.getName());
51 // -----------------------------Http------------------------------------------------------------------------
52 public RestResponse httpSendGetInternal(String url, Map<String, String> headers) throws IOException {
54 RestResponse restResponse = new RestResponse();
55 url = url.replaceAll("\\s", "%20");
56 URL obj = new URL(url);
57 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
58 // optional default is GET
59 con.setRequestMethod("GET");
60 addHttpRequestHEaders(headers, con);
62 int responseCode = con.getResponseCode();
63 logger.debug("Send GET http request, url: {}",url);
64 logger.debug("Response Code: {}",responseCode);
66 StringBuffer response = new StringBuffer();
70 result = IOUtils.toString(con.getInputStream());
71 response.append(result);
72 } catch (Exception e) {
73 logger.debug("Fail with exception", e);
76 result = IOUtils.toString(con.getErrorStream());
77 response.append(result);
78 } catch (Exception e) {
79 // logger.debug("Fail with exception", e);
82 logger.debug("Response body: {}" ,response);
85 setHttpResponseToObject(restResponse, con, responseCode, response);
91 public RestResponse httpSendByMethodInternal(String url, String method, String body, Map<String, String> headers) throws IOException {
93 RestResponse restResponse = new RestResponse();
94 URL obj = new URL(url);
95 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
97 con.setRequestMethod(method);
98 // add request headers
99 addHttpRequestHEaders(headers, con);
100 if (body != null && !body.isEmpty() && !method.equals("DELETE")) {
102 con.setDoOutput(true);
103 DataOutputStream wr = new DataOutputStream(con.getOutputStream());
109 int responseCode = con.getResponseCode();
110 logger.debug("Send {} http request, url: {}",method,url);
111 logger.debug("Response Code: {}",responseCode);
113 StringBuffer response = generateHttpResponse(con, false);
116 result = IOUtils.toString(con.getErrorStream());
117 response.append(result);
118 } catch (Exception e) {
119 // logger.debug("Fail with exception", e);
121 logger.debug("Response body: {}",response);
123 setHttpResponseToObject(restResponse, con, responseCode, response);
129 public RestResponse httpSendDelete(String url, Map<String, String> headers) throws IOException {
130 if (url.matches("^(https)://.*$")){
131 return httpsSendDelete(url, headers);
133 return httpSendDeleteInternal(url, headers);
136 public RestResponse httpSendGet(String url, Map<String, String> headers) throws IOException {
137 if (url.matches("^(https)://.*$")){
138 return httpsSendGet(url, headers);
140 return httpSendGetInternal(url, headers);
143 public RestResponse httpSendByMethod(String url, String method, String body, Map<String, String> headers) throws IOException {
144 if (url.matches("^(https)://.*$")){
145 return httpsSendByMethod(url, method, body, headers);
147 return httpSendByMethodInternal(url, method, body, headers);
150 public RestResponse httpSendPost(String url, String body, Map<String, String> headers) throws IOException {
151 if (url.matches("^(https)://.*$")){
152 return httpsSendByMethod(url, "POST", body, headers);
154 return httpSendByMethod(url, "POST", body, headers);
157 public RestResponse httpSendPut(String url, String body, Map<String, String> headers) throws IOException {
158 if (url.matches("^(https)://.*$")){
159 return httpsSendByMethod(url, "PUT", body, headers);
161 return httpSendByMethod(url, "PUT", body, headers);
165 public RestResponse httpSendDeleteInternal(String url, Map<String, String> headers) throws IOException {
167 RestResponse restResponse = new RestResponse();
168 URL obj = new URL(url);
169 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
171 addHttpRequestHEaders(headers, con);
173 con.setDoOutput(true);
174 con.setRequestMethod("DELETE");
175 int responseCode = con.getResponseCode();
176 logger.debug("Send DELETE http request, url: {}",url);
177 logger.debug("Response Code: {}",responseCode);
179 StringBuffer response = generateHttpResponse(con, false);
182 result = IOUtils.toString(con.getErrorStream());
183 response.append(result);
184 } catch (Exception e) {
185 // logger.debug("Fail with exception", e);
187 logger.debug("Response body: {}",response);
190 setHttpResponseToObject(restResponse, con, responseCode, response);
196 public static RestResponse sendHttpPostWithEntity(HttpEntity requestEntity, String url, Map<String, String> headers) throws IOException {
197 CloseableHttpResponse response = null;
198 CloseableHttpClient client = HttpClients.createDefault();
200 HttpPost httpPost = new HttpPost(url);
201 RestResponse restResponse = new RestResponse();
202 for (Entry<String, String> entry : headers.entrySet()) {
203 httpPost.addHeader(entry.getKey(), entry.getValue());
206 httpPost.setEntity(requestEntity);
207 response = client.execute(httpPost);
208 HttpEntity responseEntity = response.getEntity();
209 String responseBody = null;
210 if (responseEntity != null) {
211 InputStream instream = responseEntity.getContent();
212 StringWriter writer = new StringWriter();
213 IOUtils.copy(instream, writer);
214 responseBody = writer.toString();
222 restResponse.setErrorCode(response.getStatusLine().getStatusCode());
223 restResponse.setResponse(responseBody);
228 closeResponse(response);
229 closeHttpClient(client);
234 private static void closeHttpClient(CloseableHttpClient client) {
236 if (client != null) {
239 } catch (IOException e) {
240 logger.debug("failed to close client or response: ", e);
244 private static void closeResponse(CloseableHttpResponse response) {
246 if (response != null) {
249 } catch (IOException e) {
250 logger.debug("failed to close client or response: ", e);
255 // -----------------------------Https------------------------------------------------------------------------
256 public RestResponse httpsSendGet(String url, Map<String, String> headers) throws IOException {
258 RestResponse restResponse = new RestResponse();
259 url = url.replaceAll("\\s", "%20");
260 URL obj = new URL(null, url, new sun.net.www.protocol.https.Handler());
261 HttpsURLConnection con = (HttpsURLConnection)obj.openConnection();
262 // optional default is GET
263 con.setRequestMethod("GET");
264 HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();
265 con.setHostnameVerifier(hostnameVerifier);
266 addHttpsRequestHeaders(headers, con);
267 Boolean multiPart = false;
268 if(headers.get(HttpHeaderEnum.ACCEPT.getValue()) != null) {
269 if (headers.get(HttpHeaderEnum.ACCEPT.getValue()).equals(BaseRestUtils.acceptMultipartHeader)) {
273 int responseCode = con.getResponseCode();
274 logger.debug("Send GET http request, url: {}",url);
275 logger.debug("Response Code: {}",responseCode);
277 StringBuffer response = generateHttpsResponse(con, multiPart);
280 if(con.getErrorStream()!=null) {
281 result = IOUtils.toString(con.getErrorStream());
282 response.append(result);
284 } catch (Exception e) {
285 // logger.debug("Fail with exception", e);
287 logger.debug("Response body: {}",response);
289 setHttpsResponseToObject(restResponse, con, responseCode, response);
296 public RestResponse httpsSendPost(String url, String body, Map<String, String> headers) throws IOException {
298 RestResponse restResponse = new RestResponse();
299 URL obj = new URL(null, url, new sun.net.www.protocol.https.Handler());
300 HttpsURLConnection con = (HttpsURLConnection)obj.openConnection();
301 HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();
302 con.setHostnameVerifier(hostnameVerifier);
303 // add request method
304 con.setRequestMethod("POST");
305 // add request headers
306 addHttpRequestHEaders(headers, con);
309 con.setDoOutput(true);
310 DataOutputStream wr = new DataOutputStream(con.getOutputStream());
315 int responseCode = con.getResponseCode();
316 logger.debug("Send POST http request, url: {}",url);
317 logger.debug("Response Code: {}",responseCode);
319 StringBuffer response = generateHttpsResponse(con, false);
322 if(con.getErrorStream()!=null) {
323 result = IOUtils.toString(con.getErrorStream());
324 response.append(result);
326 } catch (Exception e) {
327 // logger.debug("Fail with exception", e);
329 logger.debug("Response body: {}",response);
331 setHttpResponseToObject(restResponse, con, responseCode, response);
337 public RestResponse httpsSendByMethod(String url, String method, String body, Map<String, String> headers) throws IOException {
339 RestResponse restResponse = new RestResponse();
340 URL obj = new URL(null, url, new sun.net.www.protocol.https.Handler());
341 HttpsURLConnection con = (HttpsURLConnection)obj.openConnection();
342 HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();
343 con.setHostnameVerifier(hostnameVerifier);
344 // add request method
345 con.setRequestMethod(method);
346 // add request headers
347 addHttpRequestHEaders(headers, con);
348 if (body != null && !body.isEmpty() && !method.equals("DELETE")) {
350 con.setDoOutput(true);
351 DataOutputStream wr = new DataOutputStream(con.getOutputStream());
357 int responseCode = con.getResponseCode();
358 logger.debug("Send {} http request, url: {}",method,url);
359 logger.debug("Response Code: {}",responseCode);
361 StringBuffer response = generateHttpResponse(con, false);
364 if(con.getErrorStream()!=null) {
365 result = IOUtils.toString(con.getErrorStream());
366 response.append(result);
368 } catch (Exception e) {
369 // logger.debug("Fail with exception", e);
371 logger.debug("Response body: {}",response);
373 setHttpResponseToObject(restResponse, con, responseCode, response);
380 public RestResponse httpsSendDelete(String url, Map<String, String> headers) throws IOException {
382 RestResponse restResponse = new RestResponse();
383 URL obj = new URL(null, url, new sun.net.www.protocol.https.Handler());
384 HttpsURLConnection con = (HttpsURLConnection)obj.openConnection();
385 HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();
386 con.setHostnameVerifier(hostnameVerifier);
387 // add request headers
388 addHttpRequestHEaders(headers, con);
390 con.setDoOutput(true);
391 con.setRequestMethod("DELETE");
392 int responseCode = con.getResponseCode();
393 logger.debug("Send DELETE http request, url: {}",url);
394 logger.debug("Response Code: {}",responseCode);
396 StringBuffer response = generateHttpsResponse(con, false);
399 if(con.getErrorStream()!=null) {
400 result = IOUtils.toString(con.getErrorStream());
401 response.append(result);
403 } catch (Exception e) {
404 // logger.debug("Fail with exception", e);
406 logger.debug("Response body: {}",response);
408 setHttpResponseToObject(restResponse, con, responseCode, response);
414 // ---------------------------------------
415 private void addHttpsRequestHeaders(Map<String, String> headers, HttpsURLConnection con) {
416 // add request header
417 if (headers != null) {
418 for (Entry<String, String> header : headers.entrySet()) {
419 String key = header.getKey();
420 String value = header.getValue();
421 con.setRequestProperty(key, value);
427 private void addHttpRequestHEaders(Map<String, String> headers, HttpURLConnection con) {
428 // add request header
429 if (headers != null) {
430 for (Entry<String, String> header : headers.entrySet()) {
431 String key = header.getKey();
432 String value = header.getValue();
433 con.setRequestProperty(key, value);
439 private void setHttpResponseToObject(RestResponse restResponse, HttpURLConnection con, int responseCode, StringBuffer response) throws IOException {
440 restResponse.setErrorCode(responseCode);
442 if (response != null) {
443 restResponse.setResponse(response.toString());
446 Map<String, List<String>> headerFields = con.getHeaderFields();
447 restResponse.setHeaderFields(headerFields);
448 String responseMessage = con.getResponseMessage();
449 restResponse.setResponseMessage(responseMessage);
452 private StringBuffer generateHttpResponse(HttpURLConnection con, Boolean isMultiPart) {
453 StringBuffer response = new StringBuffer();
454 StringWriter writer = new StringWriter();
457 IOUtils.copy((con.getInputStream()), writer, Charset.forName("UTF-8"));
458 response = writer.getBuffer();
461 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
463 while ((inputLine = in.readLine()) != null) {
464 response.append(inputLine);
468 } catch (Exception e) {
469 logger.debug("response body is null");
475 private void setHttpsResponseToObject(RestResponse restResponse, HttpsURLConnection con, int responseCode, StringBuffer response) throws IOException {
476 if (response != null) {
477 restResponse.setResponse(response.toString());
480 restResponse.setErrorCode(responseCode);
481 // restResponse.setResponse(result);
482 Map<String, List<String>> headerFields = con.getHeaderFields();
483 restResponse.setHeaderFields(headerFields);
484 String responseMessage = con.getResponseMessage();
485 restResponse.setResponseMessage(responseMessage);
488 private StringBuffer generateHttpsResponse(HttpsURLConnection con, Boolean isMultiPart) {
489 StringBuffer response = new StringBuffer();
490 StringWriter writer = new StringWriter();
493 IOUtils.copy((con.getInputStream()), writer, Charset.forName("UTF-8"));
494 response = writer.getBuffer();
497 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
499 while ((inputLine = in.readLine()) != null) {
500 response.append(inputLine);
504 } catch (Exception e) {
505 logger.debug("response body is null");
513 class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
514 public static final String METHOD_NAME = "DELETE";
516 public String getMethod() {
520 public HttpDeleteWithBody(final String uri) {
522 setURI(URI.create(uri));
525 public HttpDeleteWithBody(final URI uri) {
530 public HttpDeleteWithBody() {