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.onap.sdc.ci.tests.datatypes.http;
23 import java.io.BufferedReader;
24 import java.io.DataOutputStream;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.InputStreamReader;
29 import java.io.StringWriter;
30 import java.net.HttpURLConnection;
33 import java.util.List;
35 import java.util.Map.Entry;
36 import java.util.Scanner;
38 import javax.net.ssl.HttpsURLConnection;
40 import org.apache.commons.codec.binary.Base64;
41 import org.apache.commons.io.IOUtils;
42 import org.apache.http.HttpEntity;
43 import org.apache.http.annotation.NotThreadSafe;
44 import org.apache.http.client.ClientProtocolException;
45 import org.apache.http.client.methods.CloseableHttpResponse;
46 import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
47 import org.apache.http.client.methods.HttpPost;
48 import org.apache.http.entity.ContentType;
49 import org.apache.http.entity.StringEntity;
50 import org.apache.http.entity.mime.MultipartEntityBuilder;
51 import org.apache.http.entity.mime.content.FileBody;
52 import org.apache.http.entity.mime.content.StringBody;
53 import org.apache.http.impl.client.CloseableHttpClient;
54 import org.apache.http.impl.client.HttpClients;
55 import org.apache.http.util.EntityUtils;
56 import org.onap.sdc.ci.tests.datatypes.http.RestResponse;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
60 import com.google.gson.Gson;
62 public class HttpRequest {
63 static Logger logger = LoggerFactory.getLogger(HttpRequest.class.getName());
65 public RestResponse httpSendGet(String url, Map<String, String> headers) throws IOException {
67 RestResponse restResponse = new RestResponse();
68 url = url.replaceAll("\\s", "%20");
69 URL obj = new URL(url);
70 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
71 // optional default is GET
72 con.setRequestMethod("GET");
74 if (headers != null) {
75 for (Entry<String, String> header : headers.entrySet()) {
76 String key = header.getKey();
77 String value = header.getValue();
78 con.setRequestProperty(key, value);
83 int responseCode = con.getResponseCode();
84 logger.debug("Send GET http request, url: {}",url);
85 logger.debug("Response Code: {}",responseCode);
87 StringBuffer response = new StringBuffer();
92 result = IOUtils.toString(con.getInputStream());
93 response.append(result);
95 } catch (Exception e) {
100 result = IOUtils.toString(con.getErrorStream());
101 response.append(result);
103 } catch (Exception e) {
106 logger.debug("Response body: {}" ,response);
110 restResponse.setStatusCode(responseCode);
112 if (response != null) {
113 restResponse.setResponse(response.toString());
116 restResponse.setStatusCode(responseCode);
117 Map<String, List<String>> headerFields = con.getHeaderFields();
118 restResponse.setHeaderFields(headerFields);
119 String responseMessage = con.getResponseMessage();
120 restResponse.setResponseMessage(responseMessage);
127 public RestResponse httpsSendGet(String url, Map<String, String> headers) throws IOException {
129 RestResponse restResponse = new RestResponse();
130 URL obj = new URL(url);
131 HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
132 // optional default is GET
133 con.setRequestMethod("GET");
134 // add request header
135 if (headers != null) {
136 for (Entry<String, String> header : headers.entrySet()) {
137 String key = header.getKey();
138 String value = header.getValue();
139 con.setRequestProperty(key, value);
144 int responseCode = con.getResponseCode();
145 logger.debug("Send GET http request, url: {}",url);
146 logger.debug("Response Code: {}",responseCode);
148 StringBuffer response = new StringBuffer();
150 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
152 while ((inputLine = in.readLine()) != null) {
153 response.append(inputLine);
156 } catch (Exception e) {
157 logger.debug("response body is null");
164 result = IOUtils.toString(con.getErrorStream());
165 response.append(result);
167 } catch (Exception e2) {
170 logger.debug("Response body: {}",response);
174 restResponse.setStatusCode(responseCode);
176 if (response != null) {
177 restResponse.setResponse(response.toString());
180 restResponse.setStatusCode(responseCode);
181 // restResponse.setResponse(result);
182 Map<String, List<String>> headerFields = con.getHeaderFields();
183 restResponse.setHeaderFields(headerFields);
184 String responseMessage = con.getResponseMessage();
185 restResponse.setResponseMessage(responseMessage);
192 public RestResponse httpSendByMethod(String url, String method, String body, Map<String, String> headers)
195 RestResponse restResponse = new RestResponse();
196 URL obj = new URL(url);
197 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
199 // add request method
200 con.setRequestMethod(method);
202 // add request headers
203 if (headers != null) {
204 for (Entry<String, String> header : headers.entrySet()) {
205 String key = header.getKey();
206 String value = header.getValue();
207 con.setRequestProperty(key, value);
211 if (body != null && !body.isEmpty() && !method.equals("DELETE")) {
213 con.setDoOutput(true);
214 DataOutputStream wr = new DataOutputStream(con.getOutputStream());
222 int responseCode = con.getResponseCode();
223 logger.debug("Send {} http request, url: {}",method,url);
224 logger.debug("Response Code: {}",responseCode);
226 StringBuffer response = new StringBuffer();
229 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
231 while ((inputLine = in.readLine()) != null) {
232 response.append(inputLine);
235 } catch (Exception e) {
237 logger.debug("response body is null");
243 result = IOUtils.toString(con.getErrorStream());
244 response.append(result);
246 } catch (Exception e2) {
249 logger.debug("Response body: {}",response);
253 restResponse.setStatusCode(responseCode);
254 // if (response == null) {
255 // restResponse.setResponse(null);
257 // restResponse.setResponse(response.toString());
260 if (response != null) {
261 restResponse.setResponse(response.toString());
263 Map<String, List<String>> headerFields = con.getHeaderFields();
264 restResponse.setHeaderFields(headerFields);
265 String responseMessage = con.getResponseMessage();
266 restResponse.setResponseMessage(responseMessage);
273 public RestResponse sendHttpPost(String url, String body, Map<String, String> headers) throws IOException {
275 RestResponse restResponse = new RestResponse();
276 URL obj = new URL(url);
277 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
279 // add request method
280 con.setRequestMethod("POST");
282 // add request headers
283 if (headers != null) {
284 for (Entry<String, String> header : headers.entrySet()) {
285 String key = header.getKey();
286 String value = header.getValue();
287 con.setRequestProperty(key, value);
293 con.setDoOutput(true);
294 DataOutputStream wr = new DataOutputStream(con.getOutputStream());
302 int responseCode = con.getResponseCode();
303 logger.debug("Send POST http request, url: {}",url);
304 logger.debug("Response Code: {}",responseCode);
306 StringBuffer response = new StringBuffer();
308 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
310 while ((inputLine = in.readLine()) != null) {
311 response.append(inputLine);
314 } catch (Exception e) {
315 logger.debug("response body is null");
322 result = IOUtils.toString(con.getErrorStream());
323 response.append(result);
325 } catch (Exception e2) {
328 logger.debug("Response body: {}",response);
332 restResponse.setStatusCode(responseCode);
334 if (response != null) {
335 restResponse.setResponse(response.toString());
338 Map<String, List<String>> headerFields = con.getHeaderFields();
339 restResponse.setHeaderFields(headerFields);
340 String responseMessage = con.getResponseMessage();
341 restResponse.setResponseMessage(responseMessage);
348 public RestResponse httpSendPost(String url, String body, Map<String, String> headers) throws IOException {
349 return httpSendPost(url, body, headers, "POST");
352 public RestResponse httpSendPut(String url, String body, Map<String, String> headers) throws IOException {
353 return httpSendPost(url, body, headers, "PUT");
356 public RestResponse httpSendPost(String url, String body, Map<String, String> headers, String methodType)
359 RestResponse restResponse = new RestResponse();
360 URL obj = new URL(url);
361 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
363 // add request method
364 con.setRequestMethod(methodType);
366 // add request headers
367 if (headers != null) {
368 for (Entry<String, String> header : headers.entrySet()) {
369 String key = header.getKey();
370 String value = header.getValue();
371 con.setRequestProperty(key, value);
377 con.setDoOutput(true);
378 DataOutputStream wr = new DataOutputStream(con.getOutputStream());
386 int responseCode = con.getResponseCode();
387 logger.debug("Send POST http request, url: {}",url);
388 logger.debug("Response Code: {}",responseCode);
390 StringBuffer response = new StringBuffer();
392 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
394 while ((inputLine = in.readLine()) != null) {
395 response.append(inputLine);
398 } catch (Exception e) {
399 logger.debug("response body is null");
406 result = IOUtils.toString(con.getErrorStream());
407 response.append(result);
409 } catch (Exception e2) {
412 logger.debug("Response body: {}",response);
416 restResponse.setStatusCode(responseCode);
418 if (response != null) {
419 restResponse.setResponse(response.toString());
422 Map<String, List<String>> headerFields = con.getHeaderFields();
423 restResponse.setHeaderFields(headerFields);
424 String responseMessage = con.getResponseMessage();
425 restResponse.setResponseMessage(responseMessage);
432 public RestResponse httpSendDeleteWithBody2(String url, String body, Map<String, String> headers)
433 throws ClientProtocolException, IOException {
435 CloseableHttpClient httpclient = HttpClients.createDefault();
436 RestResponse restResponse = new RestResponse();
437 HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url);
439 // add request headers
440 if (headers != null) {
441 for (Entry<String, String> header : headers.entrySet()) {
442 String key = header.getKey();
443 String value = header.getValue();
444 httpDelete.addHeader(key, value);
448 // add body to request
449 StringEntity input = new StringEntity(body, ContentType.APPLICATION_JSON);
450 httpDelete.setEntity(input);
453 CloseableHttpResponse response = httpclient.execute(httpDelete);
455 restResponse.setStatusCode(response.getStatusLine().getStatusCode());
460 public RestResponse httpSendDeleteWithBody(String url, String body, Map<String, String> headers)
463 RestResponse restResponse = new RestResponse();
464 URL obj = new URL(url);
465 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
467 // add request method
468 con.setRequestMethod("DELETE");
470 // add request headers
471 if (headers != null) {
472 for (Entry<String, String> header : headers.entrySet()) {
473 String key = header.getKey();
474 String value = header.getValue();
475 con.setRequestProperty(key, value);
480 con.setDoOutput(true);
481 DataOutputStream wr = new DataOutputStream(con.getOutputStream());
488 int responseCode = con.getResponseCode();
489 logger.debug("Send DELETE http request, url: {}",url);
490 logger.debug("Response Code: {}",responseCode);
492 StringBuffer response = new StringBuffer();
494 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
496 while ((inputLine = in.readLine()) != null) {
497 response.append(inputLine);
500 } catch (Exception e) {
501 logger.debug("response body is null");
508 result = IOUtils.toString(con.getErrorStream());
509 response.append(result);
511 } catch (Exception e2) {
514 logger.debug("Response body: {}", response);
518 restResponse.setStatusCode(responseCode);
520 if (response != null) {
521 restResponse.setResponse(response.toString());
524 Map<String, List<String>> headerFields = con.getHeaderFields();
525 restResponse.setHeaderFields(headerFields);
526 String responseMessage = con.getResponseMessage();
527 restResponse.setResponseMessage(responseMessage);
534 public RestResponse httpSendPostWithOutBody(String url, Map<String, String> headers) throws IOException {
536 RestResponse restResponse = new RestResponse();
537 URL obj = new URL(url);
538 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
540 // add request method
541 con.setRequestMethod("POST");
543 // add request headers
544 if (headers != null) {
545 for (Entry<String, String> header : headers.entrySet()) {
546 String key = header.getKey();
547 String value = header.getValue();
548 con.setRequestProperty(key, value);
554 int responseCode = con.getResponseCode();
555 logger.debug("Send POST http request, url: {}",url);
556 logger.debug("Response Code: {}",responseCode);
558 StringBuffer response = new StringBuffer();
561 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
563 while ((inputLine = in.readLine()) != null) {
564 response.append(inputLine);
567 } catch (Exception e) {
569 logger.debug("response body is null");
575 result = IOUtils.toString(con.getErrorStream());
576 response.append(result);
578 } catch (Exception e2) {
581 logger.debug("Response body: {}",response);
585 restResponse.setStatusCode(responseCode);
586 // if (response == null) {
587 // restResponse.setResponse(null);
589 // restResponse.setResponse(response.toString());
592 if (response != null) {
593 restResponse.setResponse(response.toString());
596 Map<String, List<String>> headerFields = con.getHeaderFields();
597 restResponse.setHeaderFields(headerFields);
598 String responseMessage = con.getResponseMessage();
599 restResponse.setResponseMessage(responseMessage);
606 public RestResponse httpSendPostMultipart(String url, Map<String, String> headers, String jsonLocation,
607 String zipLocation) throws IOException {
609 Gson gson = new Gson();
610 String gsonToSend = null;
611 RestResponse restResponse = new RestResponse();
612 BufferedReader br = null;
619 // String sCurrentLine;
621 // br = new BufferedReader(new FileReader(jsonLocation));
623 // while ((sCurrentLine = br.readLine()) != null) {
624 // System.out.println(sCurrentLine);
627 // } catch (IOException e) {
628 // e.printStackTrace();
631 // if (br != null)br.close();
632 // gsonToSend = br.toString();
633 // } catch (IOException ex) {
634 // ex.printStackTrace();
638 gsonToSend = new Scanner(new File(jsonLocation)).useDelimiter("\\Z").next();
639 logger.debug("gsonToSend: {}",gsonToSend);
641 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
642 mpBuilder.addPart("resourceZip", new FileBody(new File(zipLocation)));
643 mpBuilder.addPart("resourceMetadata", new StringBody(gsonToSend, ContentType.APPLICATION_JSON));
645 HttpPost httpPost = new HttpPost(url);
646 httpPost.addHeader("USER_ID", "adminid");
647 httpPost.setEntity(mpBuilder.build());
649 CloseableHttpClient client = HttpClients.createDefault();
650 CloseableHttpResponse response = client.execute(httpPost);
652 logger.debug("----------------------------------------");
653 logger.debug("response.getStatusLine(): {}",response.getStatusLine());
654 HttpEntity resEntity = response.getEntity();
655 if (resEntity != null) {
656 logger.debug("Response content length: {}",resEntity.getContentLength());
658 EntityUtils.consume(resEntity);
665 restResponse.setStatusCode(response.getStatusLine().getStatusCode());
666 restResponse.setResponse(response.getEntity().toString());
672 public RestResponse httpSendPostWithAuth(String url, String body, Map<String, String> headers, String username,
673 String password) throws IOException {
675 String userPassword = username + ":" + password;
676 String encoding = Base64.encodeBase64String(userPassword.getBytes());
677 RestResponse restResponse = new RestResponse();
678 URL obj = new URL(url);
679 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
681 // add request method
682 con.setRequestMethod("POST");
684 con.setRequestProperty("Authorization", "Basic " + encoding);
686 // add request headers
687 if (headers != null) {
688 for (Entry<String, String> header : headers.entrySet()) {
689 String key = header.getKey();
690 String value = header.getValue();
691 con.setRequestProperty(key, value);
697 con.setDoOutput(true);
698 DataOutputStream wr = new DataOutputStream(con.getOutputStream());
705 int responseCode = con.getResponseCode();
706 logger.debug("Send POST http request, url: {}",url);
707 logger.debug("Response Code: {}",responseCode);
709 StringBuffer response = new StringBuffer();
711 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
713 while ((inputLine = in.readLine()) != null) {
714 response.append(inputLine);
717 } catch (Exception e) {
721 logger.debug("Response body: {}",response);
725 restResponse.setStatusCode(responseCode);
726 if (response == null) {
727 restResponse.setResponse(null);
729 restResponse.setResponse(response.toString());
732 Map<String, List<String>> headerFields = con.getHeaderFields();
733 restResponse.setHeaderFields(headerFields);
734 String responseMessage = con.getResponseMessage();
735 restResponse.setResponseMessage(responseMessage);
742 public RestResponse httpSendDelete(String url, Map<String, String> headers) throws IOException {
744 RestResponse restResponse = new RestResponse();
745 URL obj = new URL(url);
746 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
748 if (headers != null) {
749 for (Entry<String, String> header : headers.entrySet()) {
750 String key = header.getKey();
751 String value = header.getValue();
752 con.setRequestProperty(key, value);
757 con.setDoOutput(true);
758 con.setRequestMethod("DELETE");
759 int responseCode = con.getResponseCode();
760 logger.debug("Send DELETE http request, url: {}",url);
761 logger.debug("Response Code: {}",responseCode);
763 StringBuffer response = new StringBuffer();
766 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
768 while ((inputLine = in.readLine()) != null) {
769 response.append(inputLine);
772 } catch (Exception e) {
773 logger.debug("response body is null");
780 result = IOUtils.toString(con.getErrorStream());
781 response.append(result);
783 } catch (Exception e2) {
786 logger.debug("Response body: {}",response);
790 restResponse.setStatusCode(responseCode);
792 if (response != null) {
793 restResponse.setResponse(response.toString());
796 restResponse.setStatusCode(con.getResponseCode());
797 Map<String, List<String>> headerFields = con.getHeaderFields();
798 restResponse.setHeaderFields(headerFields);
799 String responseMessage = con.getResponseMessage();
800 restResponse.setResponseMessage(responseMessage);
807 public static RestResponse sendHttpPostWithEntity(HttpEntity requestEntity, String url, Map<String, String> headers)
808 throws IOException, ClientProtocolException {
809 CloseableHttpResponse response = null;
810 CloseableHttpClient client = HttpClients.createDefault();
812 HttpPost httpPost = new HttpPost(url);
813 RestResponse restResponse = new RestResponse();
814 for (Entry<String, String> entry : headers.entrySet()) {
815 httpPost.addHeader(entry.getKey(), entry.getValue());
818 httpPost.setEntity(requestEntity);
819 response = client.execute(httpPost);
820 HttpEntity responseEntity = response.getEntity();
821 String responseBody = null;
822 if (responseEntity != null) {
823 InputStream instream = responseEntity.getContent();
824 StringWriter writer = new StringWriter();
825 IOUtils.copy(instream, writer);
826 responseBody = writer.toString();
834 restResponse.setStatusCode(response.getStatusLine().getStatusCode());
835 restResponse.setResponse(responseBody);
840 closeResponse(response);
841 closeHttpClient(client);
846 private static void closeHttpClient(CloseableHttpClient client) {
848 if (client != null) {
851 } catch (IOException e) {
852 logger.debug("failed to close client or response: ", e);
856 private static void closeResponse(CloseableHttpResponse response) {
858 if (response != null) {
861 } catch (IOException e) {
862 logger.debug("failed to close client or response: ", e);
867 class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
868 public static final String METHOD_NAME = "DELETE";
870 public String getMethod() {
874 public HttpDeleteWithBody(final String uri) {
876 setURI(URI.create(uri));
879 public HttpDeleteWithBody(final URI uri) {
884 public HttpDeleteWithBody() {