2 * Copyright 2017 ZTE Corporation.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org.onap.workflow.activitiext.restservicetask;
18 import org.apache.commons.httpclient.HttpClient;
19 import org.apache.commons.httpclient.HttpMethod;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
23 import com.alibaba.fastjson.JSON;
26 * This static-class eases HTTP-method execution by self-managed fault-handling
27 * and automated Response-information processing
29 public class LowLevelRestApi {
31 private static final Logger logger = LoggerFactory.getLogger(LowLevelRestApi.class);
33 // Local HttpClient used for every communication (Singleton implementation)
34 private static HttpClient httpClient = new HttpClient();
37 * Executes a passed HttpMethod (Method type is either PUT, POST, GET or
38 * DELETE) and returns a HttpResponseMessage
42 * @return HttpResponseMessage which contains all information about the
45 public static HttpResponseMessage executeHttpMethod(HttpMethod method) throws Exception {
47 HttpResponseMessage responseMessage = null;
52 LowLevelRestApi.httpClient.executeMethod(method);
53 responseMessage = LowLevelRestApi.extractResponseInformation(method);
55 logger.info("statusCode: {}", method.getStatusCode());
56 logger.info("responseBody: {}", method.getResponseBodyAsString());
57 } catch (Exception e) {
58 logger.error("visit interface failed!", e);
62 // Release Connection anyway
63 method.releaseConnection();
66 // Extract response information and return
67 return responseMessage;
71 * Extracts the response information from an executed HttpMethod
75 * @return Packaged response information
77 private static HttpResponseMessage extractResponseInformation(HttpMethod method) {
78 // Create and return HttpResponseMethod
79 HttpResponseMessage responseMessage = new HttpResponseMessage();
80 responseMessage.setStatusCode(method.getStatusCode());
82 JSON json = (JSON) JSON.parse(method.getResponseBodyAsString());
83 responseMessage.setResponseBody(json);
85 } catch (Exception e) {
86 logger.info("response is not a json!");
88 return responseMessage;