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 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.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
59 import com.google.gson.Gson;
61 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 obj = new URL(url);
69 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
70 // optional default is GET
71 con.setRequestMethod("GET");
73 if (headers != null) {
74 for (Entry<String, String> header : headers.entrySet()) {
75 String key = header.getKey();
76 String value = header.getValue();
77 con.setRequestProperty(key, value);
82 int responseCode = con.getResponseCode();
83 logger.debug("Send GET http request, url: {}", url);
84 logger.debug("Response Code: {}", responseCode);
86 StringBuffer response = new StringBuffer();
91 result = IOUtils.toString(con.getInputStream());
92 response.append(result);
94 } catch (Exception e) {
99 result = IOUtils.toString(con.getErrorStream());
100 response.append(result);
102 } catch (Exception e) {
105 logger.debug("Response body: {}", response);
109 restResponse.setErrorCode(responseCode);
111 if (response != null) {
112 restResponse.setResponse(response.toString());
115 restResponse.setErrorCode(responseCode);
116 Map<String, List<String>> headerFields = con.getHeaderFields();
117 restResponse.setHeaderFields(headerFields);
118 String responseMessage = con.getResponseMessage();
119 restResponse.setResponseMessage(responseMessage);
126 public RestResponse httpsSendGet(String url, Map<String, String> headers) throws IOException {
128 RestResponse restResponse = new RestResponse();
129 URL obj = new URL(url);
130 HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
131 // optional default is GET
132 con.setRequestMethod("GET");
133 // add request header
134 if (headers != null) {
135 for (Entry<String, String> header : headers.entrySet()) {
136 String key = header.getKey();
137 String value = header.getValue();
138 con.setRequestProperty(key, value);
143 int responseCode = con.getResponseCode();
144 logger.debug("Send GET http request, url: {}", url);
145 logger.debug("Response Code: {}", responseCode);
147 StringBuffer response = new StringBuffer();
149 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
151 while ((inputLine = in.readLine()) != null) {
152 response.append(inputLine);
155 } catch (Exception e) {
156 logger.debug("response body is null", e);
163 result = IOUtils.toString(con.getErrorStream());
164 response.append(result);
166 } catch (Exception e2) {
169 logger.debug("Response body: {}", response);
173 restResponse.setErrorCode(responseCode);
175 if (response != null) {
176 restResponse.setResponse(response.toString());
179 restResponse.setErrorCode(responseCode);
180 // restResponse.setResponse(result);
181 Map<String, List<String>> headerFields = con.getHeaderFields();
182 restResponse.setHeaderFields(headerFields);
183 String responseMessage = con.getResponseMessage();
184 restResponse.setResponseMessage(responseMessage);
191 public RestResponse httpSendByMethod(String url, String method, String body, Map<String, String> headers)
194 RestResponse restResponse = new RestResponse();
195 URL obj = new URL(url);
196 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
198 // add request method
199 con.setRequestMethod(method);
201 // add request headers
202 if (headers != null) {
203 for (Entry<String, String> header : headers.entrySet()) {
204 String key = header.getKey();
205 String value = header.getValue();
206 con.setRequestProperty(key, value);
210 if (body != null && !body.isEmpty() && !method.equals("DELETE")) {
212 con.setDoOutput(true);
213 DataOutputStream wr = new DataOutputStream(con.getOutputStream());
221 int responseCode = con.getResponseCode();
222 logger.debug("Send {} http request, url: {}", method, url);
223 logger.debug("Response Code: {}", responseCode);
225 StringBuffer response = new StringBuffer();
228 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
230 while ((inputLine = in.readLine()) != null) {
231 response.append(inputLine);
234 } catch (Exception e) {
236 logger.debug("response body is null", e);
242 result = IOUtils.toString(con.getErrorStream());
243 response.append(result);
245 } catch (Exception e2) {
248 logger.debug("Response body: {}", response);
252 restResponse.setErrorCode(responseCode);
253 // if (response == null) {
254 // restResponse.setResponse(null);
256 // restResponse.setResponse(response.toString());
259 if (response != null) {
260 restResponse.setResponse(response.toString());
262 Map<String, List<String>> headerFields = con.getHeaderFields();
263 restResponse.setHeaderFields(headerFields);
264 String responseMessage = con.getResponseMessage();
265 restResponse.setResponseMessage(responseMessage);
272 public RestResponse sendHttpPost(String url, String body, Map<String, String> headers) throws IOException {
274 RestResponse restResponse = new RestResponse();
275 URL obj = new URL(url);
276 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
278 // add request method
279 con.setRequestMethod("POST");
281 // add request headers
282 if (headers != null) {
283 for (Entry<String, String> header : headers.entrySet()) {
284 String key = header.getKey();
285 String value = header.getValue();
286 con.setRequestProperty(key, value);
292 con.setDoOutput(true);
293 DataOutputStream wr = new DataOutputStream(con.getOutputStream());
301 int responseCode = con.getResponseCode();
302 logger.debug("Send POST http request, url: {}", url);
303 logger.debug("Response Code: {}", responseCode);
305 StringBuffer response = new StringBuffer();
307 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
309 while ((inputLine = in.readLine()) != null) {
310 response.append(inputLine);
313 } catch (Exception e) {
314 logger.debug("response body is null");
321 result = IOUtils.toString(con.getErrorStream());
322 response.append(result);
324 } catch (Exception e2) {
327 logger.debug("Response body: {}", response);
331 restResponse.setErrorCode(responseCode);
333 if (response != null) {
334 restResponse.setResponse(response.toString());
337 Map<String, List<String>> headerFields = con.getHeaderFields();
338 restResponse.setHeaderFields(headerFields);
339 String responseMessage = con.getResponseMessage();
340 restResponse.setResponseMessage(responseMessage);
347 public RestResponse httpSendPost(String url, String body, Map<String, String> headers) throws IOException {
348 return httpSendPost(url, body, headers, "POST");
351 public RestResponse httpSendPut(String url, String body, Map<String, String> headers) throws IOException {
352 return httpSendPost(url, body, headers, "PUT");
355 public RestResponse httpSendPost(String url, String body, Map<String, String> headers, String methodType)
358 RestResponse restResponse = new RestResponse();
359 URL obj = new URL(url);
360 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
362 // add request method
363 con.setRequestMethod(methodType);
365 // add request headers
366 if (headers != null) {
367 for (Entry<String, String> header : headers.entrySet()) {
368 String key = header.getKey();
369 String value = header.getValue();
370 con.setRequestProperty(key, value);
376 con.setDoOutput(true);
377 DataOutputStream wr = new DataOutputStream(con.getOutputStream());
385 int responseCode = con.getResponseCode();
386 logger.debug("Send POST http request, url: {}", url);
387 logger.debug("Response Code: {}", responseCode);
389 StringBuffer response = new StringBuffer();
391 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
393 while ((inputLine = in.readLine()) != null) {
394 response.append(inputLine);
397 } catch (Exception e) {
398 logger.debug("response body is null");
405 result = IOUtils.toString(con.getErrorStream());
406 response.append(result);
408 } catch (Exception e2) {
411 logger.debug("Response body: {}", response);
415 restResponse.setErrorCode(responseCode);
417 if (response != null) {
418 restResponse.setResponse(response.toString());
421 Map<String, List<String>> headerFields = con.getHeaderFields();
422 restResponse.setHeaderFields(headerFields);
423 String responseMessage = con.getResponseMessage();
424 restResponse.setResponseMessage(responseMessage);
431 public RestResponse httpSendDeleteWithBody2(String url, String body, Map<String, String> headers)
432 throws ClientProtocolException, IOException {
434 CloseableHttpClient httpclient = HttpClients.createDefault();
435 RestResponse restResponse = new RestResponse();
436 HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url);
438 // add request headers
439 if (headers != null) {
440 for (Entry<String, String> header : headers.entrySet()) {
441 String key = header.getKey();
442 String value = header.getValue();
443 httpDelete.addHeader(key, value);
447 // add body to request
448 StringEntity input = new StringEntity(body, ContentType.APPLICATION_JSON);
449 httpDelete.setEntity(input);
452 CloseableHttpResponse response = httpclient.execute(httpDelete);
454 restResponse.setErrorCode(response.getStatusLine().getStatusCode());
459 public RestResponse httpSendDeleteWithBody(String url, String body, Map<String, String> headers)
462 RestResponse restResponse = new RestResponse();
463 URL obj = new URL(url);
464 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
466 // add request method
467 con.setRequestMethod("DELETE");
469 // add request headers
470 if (headers != null) {
471 for (Entry<String, String> header : headers.entrySet()) {
472 String key = header.getKey();
473 String value = header.getValue();
474 con.setRequestProperty(key, value);
479 con.setDoOutput(true);
480 DataOutputStream wr = new DataOutputStream(con.getOutputStream());
487 int responseCode = con.getResponseCode();
488 logger.debug("Send DELETE http request, url: {}", url);
489 logger.debug("Response Code: {}", responseCode);
491 StringBuffer response = new StringBuffer();
493 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
495 while ((inputLine = in.readLine()) != null) {
496 response.append(inputLine);
499 } catch (Exception e) {
500 logger.debug("response body is null");
507 result = IOUtils.toString(con.getErrorStream());
508 response.append(result);
510 } catch (Exception e2) {
513 logger.debug("Response body: {}", response);
517 restResponse.setErrorCode(responseCode);
519 if (response != null) {
520 restResponse.setResponse(response.toString());
523 Map<String, List<String>> headerFields = con.getHeaderFields();
524 restResponse.setHeaderFields(headerFields);
525 String responseMessage = con.getResponseMessage();
526 restResponse.setResponseMessage(responseMessage);
533 public RestResponse httpSendPostWithOutBody(String url, Map<String, String> headers) throws IOException {
535 RestResponse restResponse = new RestResponse();
536 URL obj = new URL(url);
537 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
539 // add request method
540 con.setRequestMethod("POST");
542 // add request headers
543 if (headers != null) {
544 for (Entry<String, String> header : headers.entrySet()) {
545 String key = header.getKey();
546 String value = header.getValue();
547 con.setRequestProperty(key, value);
553 int responseCode = con.getResponseCode();
554 logger.debug("Send POST http request, url: {}", url);
555 logger.debug("Response Code: {}", responseCode);
557 StringBuffer response = new StringBuffer();
560 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
562 while ((inputLine = in.readLine()) != null) {
563 response.append(inputLine);
566 } catch (Exception e) {
568 logger.debug("response body is null");
574 result = IOUtils.toString(con.getErrorStream());
575 response.append(result);
577 } catch (Exception e2) {
580 logger.debug("Response body: {}", response);
584 restResponse.setErrorCode(responseCode);
585 // if (response == null) {
586 // restResponse.setResponse(null);
588 // restResponse.setResponse(response.toString());
591 if (response != null) {
592 restResponse.setResponse(response.toString());
595 Map<String, List<String>> headerFields = con.getHeaderFields();
596 restResponse.setHeaderFields(headerFields);
597 String responseMessage = con.getResponseMessage();
598 restResponse.setResponseMessage(responseMessage);
605 public RestResponse httpSendPostMultipart(String url, Map<String, String> headers, String jsonLocation,
606 String zipLocation) throws IOException {
608 Gson gson = new Gson();
609 String gsonToSend = null;
610 RestResponse restResponse = new RestResponse();
611 BufferedReader br = null;
618 // String sCurrentLine;
620 // br = new BufferedReader(new FileReader(jsonLocation));
622 // while ((sCurrentLine = br.readLine()) != null) {
623 // System.out.println(sCurrentLine);
626 // } catch (IOException e) {
627 // e.printStackTrace();
630 // if (br != null)br.close();
631 // gsonToSend = br.toString();
632 // } catch (IOException ex) {
633 // ex.printStackTrace();
637 gsonToSend = new Scanner(new File(jsonLocation)).useDelimiter("\\Z").next();
638 logger.debug("gsonToSend: {}", gsonToSend);
640 MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
641 mpBuilder.addPart("resourceZip", new FileBody(new File(zipLocation)));
642 mpBuilder.addPart("resourceMetadata", new StringBody(gsonToSend, ContentType.APPLICATION_JSON));
644 HttpPost httpPost = new HttpPost(url);
645 httpPost.addHeader("USER_ID", "adminid");
646 httpPost.setEntity(mpBuilder.build());
648 CloseableHttpClient client = HttpClients.createDefault();
649 CloseableHttpResponse response = client.execute(httpPost);
651 logger.debug("----------------------------------------");
652 logger.debug("response.getStatusLine(): {}", response.getStatusLine());
653 HttpEntity resEntity = response.getEntity();
654 if (resEntity != null) {
655 logger.debug("Response content length: {}", resEntity.getContentLength());
657 EntityUtils.consume(resEntity);
664 restResponse.setErrorCode(response.getStatusLine().getStatusCode());
665 restResponse.setResponse(response.getEntity().toString());
671 public RestResponse httpSendPostWithAuth(String url, String body, Map<String, String> headers, String username,
672 String password) throws IOException {
674 String userPassword = username + ":" + password;
675 String encoding = Base64.encodeBase64String(userPassword.getBytes());
676 RestResponse restResponse = new RestResponse();
677 URL obj = new URL(url);
678 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
680 // add request method
681 con.setRequestMethod("POST");
683 con.setRequestProperty("Authorization", "Basic " + encoding);
685 // add request headers
686 if (headers != null) {
687 for (Entry<String, String> header : headers.entrySet()) {
688 String key = header.getKey();
689 String value = header.getValue();
690 con.setRequestProperty(key, value);
696 con.setDoOutput(true);
697 DataOutputStream wr = new DataOutputStream(con.getOutputStream());
704 int responseCode = con.getResponseCode();
705 logger.debug("Send POST http request, url: {}", url);
706 logger.debug("Response Code: {}", responseCode);
708 StringBuffer response = new StringBuffer();
710 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
712 while ((inputLine = in.readLine()) != null) {
713 response.append(inputLine);
716 } catch (Exception e) {
720 logger.debug("Response body: {}", response);
724 restResponse.setErrorCode(responseCode);
725 if (response == null) {
726 restResponse.setResponse(null);
728 restResponse.setResponse(response.toString());
731 Map<String, List<String>> headerFields = con.getHeaderFields();
732 restResponse.setHeaderFields(headerFields);
733 String responseMessage = con.getResponseMessage();
734 restResponse.setResponseMessage(responseMessage);
741 public RestResponse httpSendDelete(String url, Map<String, String> headers) throws IOException {
743 RestResponse restResponse = new RestResponse();
744 URL obj = new URL(url);
745 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
747 if (headers != null) {
748 for (Entry<String, String> header : headers.entrySet()) {
749 String key = header.getKey();
750 String value = header.getValue();
751 con.setRequestProperty(key, value);
756 con.setDoOutput(true);
757 con.setRequestMethod("DELETE");
758 int responseCode = con.getResponseCode();
759 logger.debug("Send DELETE http request, url: {}", url);
760 logger.debug("Response Code: {}", responseCode);
762 StringBuffer response = new StringBuffer();
765 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
767 while ((inputLine = in.readLine()) != null) {
768 response.append(inputLine);
771 } catch (Exception e) {
772 logger.debug("response body is null");
779 result = IOUtils.toString(con.getErrorStream());
780 response.append(result);
782 } catch (Exception e2) {
785 logger.debug("Response body: {}", response);
789 restResponse.setErrorCode(responseCode);
791 if (response != null) {
792 restResponse.setResponse(response.toString());
795 restResponse.setErrorCode(con.getResponseCode());
796 Map<String, List<String>> headerFields = con.getHeaderFields();
797 restResponse.setHeaderFields(headerFields);
798 String responseMessage = con.getResponseMessage();
799 restResponse.setResponseMessage(responseMessage);
806 public static RestResponse sendHttpPostWithEntity(HttpEntity requestEntity, String url, Map<String, String> headers)
807 throws IOException, ClientProtocolException {
808 CloseableHttpResponse response = null;
809 CloseableHttpClient client = HttpClients.createDefault();
811 HttpPost httpPost = new HttpPost(url);
812 RestResponse restResponse = new RestResponse();
813 for (Entry<String, String> entry : headers.entrySet()) {
814 httpPost.addHeader(entry.getKey(), entry.getValue());
817 httpPost.setEntity(requestEntity);
818 response = client.execute(httpPost);
819 HttpEntity responseEntity = response.getEntity();
820 String responseBody = null;
821 if (responseEntity != null) {
822 InputStream instream = responseEntity.getContent();
823 StringWriter writer = new StringWriter();
824 IOUtils.copy(instream, writer);
825 responseBody = writer.toString();
833 restResponse.setErrorCode(response.getStatusLine().getStatusCode());
834 restResponse.setResponse(responseBody);
839 closeResponse(response);
840 closeHttpClient(client);
845 private static void closeHttpClient(CloseableHttpClient client) {
847 if (client != null) {
850 } catch (IOException e) {
851 logger.debug("failed to close client or response: ", e);
855 private static void closeResponse(CloseableHttpResponse response) {
857 if (response != null) {
860 } catch (IOException e) {
861 logger.debug("failed to close client or response: ", e);
866 class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
867 public static final String METHOD_NAME = "DELETE";
869 public String getMethod() {
873 public HttpDeleteWithBody(final String uri) {
875 setURI(URI.create(uri));
878 public HttpDeleteWithBody(final URI uri) {
883 public HttpDeleteWithBody() {