update link to upper-constraints.txt
[msb/apigateway.git] / apiroute / apiroute-service / src / main / java / org / onap / msb / apiroute / wrapper / util / HttpClientUtil.java
1 /*******************************************************************************
2  * Copyright 2016-2017 ZTE, Inc. and others.
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5  * in compliance with the License. You may obtain a copy of the License at
6  * 
7  * http://www.apache.org/licenses/LICENSE-2.0
8  * 
9  * Unless required by applicable law or agreed to in writing, software distributed under the License
10  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11  * or implied. See the License for the specific language governing permissions and limitations under
12  * the License.
13  ******************************************************************************/
14 package org.onap.msb.apiroute.wrapper.util;
15
16 import java.io.IOException;
17 import java.nio.charset.Charset;
18 import java.util.ArrayList;
19 import java.util.List;
20
21 import org.apache.http.HttpMessage;
22 import org.apache.http.NameValuePair;
23 import org.apache.http.client.ClientProtocolException;
24 import org.apache.http.client.config.RequestConfig;
25 import org.apache.http.client.methods.CloseableHttpResponse;
26 import org.apache.http.client.methods.HttpDelete;
27 import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
28 import org.apache.http.client.methods.HttpGet;
29 import org.apache.http.client.methods.HttpPost;
30 import org.apache.http.client.methods.HttpPut;
31 import org.apache.http.client.utils.URLEncodedUtils;
32 import org.apache.http.entity.StringEntity;
33 import org.apache.http.impl.client.CloseableHttpClient;
34 import org.apache.http.impl.client.HttpClients;
35 import org.apache.http.message.BasicNameValuePair;
36 import org.apache.http.util.EntityUtils;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 public class HttpClientUtil {
41
42     private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
43
44     private static int connectionTimeOut = 2 * 1000;
45
46     public static HttpPost createHttpPost(String url, Object bean) throws Exception {
47         HttpPost httpPost = new HttpPost(url);
48         setCommonHeader(httpPost);
49         setStringEntity(httpPost, bean);
50         return httpPost;
51     }
52
53     public static HttpGet createHttpGet(String url) {
54         HttpGet httpGet = new HttpGet(url);
55         setCommonHeader(httpGet);
56         return httpGet;
57     }
58
59     public static HttpPut createHttpPut(String url, Object bean) throws Exception {
60         HttpPut httpPut = new HttpPut(url);
61         setCommonHeader(httpPut);
62         setStringEntity(httpPut, bean);
63         return httpPut;
64     }
65
66     public static HttpPut createHttpPut(String url) throws Exception {
67         HttpPut httpPut = new HttpPut(url);
68         setCommonHeader(httpPut);
69         return httpPut;
70     }
71
72     private static void setCommonHeader(HttpMessage httpMessage) {
73         httpMessage.addHeader("Content-type", "application/json; charset=utf-8");
74         httpMessage.setHeader("Accept", "application/json");
75     }
76
77     private static void setStringEntity(HttpEntityEnclosingRequestBase httpMessage, Object bean) throws Exception {
78         String entity = JacksonJsonUtil.beanToJson(bean);
79         httpMessage.setEntity(new StringEntity(entity, Charset.forName("UTF-8")));
80     }
81
82     public static void closeHttpClient(CloseableHttpClient httpClient, CloseableHttpResponse response) {
83         closeHttpClient(httpClient);
84         closeHttpResponse(response);
85     }
86
87     private static void closeHttpClient(CloseableHttpClient httpClient) {
88         if (httpClient != null) {
89             try {
90                 httpClient.close();
91             } catch (IOException e) {
92                 logger.error(httpClient + ":close  httpClient faild");
93             }
94         }
95     }
96
97     private static void closeHttpResponse(CloseableHttpResponse response) {
98         if (response != null) {
99             try {
100                 response.close();
101             } catch (IOException e) {
102                 logger.error(response + ":close  response faild");
103             }
104         }
105     }
106
107     public static CloseableHttpResponse httpGetWithResponse(String url) throws Exception {
108         CloseableHttpClient httpClient = HttpClients.createDefault();
109         HttpGet httpGet = new HttpGet(url);
110         httpGet.addHeader("Content-type", "application/json; charset=utf-8");
111         httpGet.setHeader("Accept", "application/json");
112         try {
113             return httpClient.execute(httpGet);
114         } finally {
115             try {
116                 httpClient.close();
117             } catch (IOException e) {
118                 logger.error(url + ":close  httpClient faild");
119             }
120         }
121     }
122
123     public static void delete(String url, String parameter) throws Exception {
124         String result = null;
125         String baseUrl;
126         if (parameter != null) {
127             List<NameValuePair> params = new ArrayList<NameValuePair>();
128             params.add(new BasicNameValuePair("serviceName", parameter));
129             baseUrl = url + "?" + URLEncodedUtils.format(params, "UTF-8");
130         } else {
131             baseUrl = url;
132         }
133
134         CloseableHttpClient httpClient = HttpClients.createDefault();;
135         try {
136
137             HttpDelete httpDelete = new HttpDelete(baseUrl);
138             CloseableHttpResponse res = httpClient.execute(httpDelete);
139
140             if (res.getStatusLine().getStatusCode() != 200) {
141                 throw new Exception("delete fail");
142             }
143
144             res.close();
145         } catch (IOException e) {
146             String errorMsg = baseUrl + ":delete connect faild";
147         } finally {
148             try {
149                 httpClient.close();
150             } catch (IOException e) {
151                 String errorMsg = baseUrl + ":close  httpClient faild";
152             }
153         }
154
155     }
156
157
158     public static String httpGet(String url) {
159         String result = null;
160         CloseableHttpClient httpClient = HttpClients.createDefault();
161         HttpGet httpGet = new HttpGet(url);
162         httpGet.addHeader("Content-type", "application/json; charset=utf-8");
163         httpGet.setHeader("Accept", "application/json");
164         try {
165             CloseableHttpResponse res = httpClient.execute(httpGet);
166             result = EntityUtils.toString(res.getEntity());
167             if (res.getStatusLine().getStatusCode() != CommonUtil.SC_OK) {
168                 logger.error(result);
169             }
170             res.close();
171         } catch (ClientProtocolException e) {
172             logger.error(url + ":httpGetWithJSON connect faild");
173         } catch (IOException e) {
174             logger.error(url + ":httpGetWithJSON connect faild");
175         } finally {
176             try {
177                 httpClient.close();
178             } catch (IOException e) {
179                 logger.error(url + ":close  httpClient faild");
180             }
181         }
182
183         return result;
184
185     }
186
187     public static HttpGetResult httpGetStatusAndBody(String url) {
188         HttpGetResult result = new HttpGetResult();
189         String body = null;
190         CloseableHttpClient httpClient = HttpClients.createDefault();
191         HttpGet httpGet = new HttpGet(url);
192         httpGet.addHeader("Content-type", "application/json; charset=utf-8");
193         httpGet.setHeader("Accept", "application/json");
194
195         RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectionTimeOut).build();
196         httpGet.setConfig(requestConfig);
197
198         try {
199             CloseableHttpResponse res = httpClient.execute(httpGet);
200             body = EntityUtils.toString(res.getEntity());
201             if (res.getStatusLine().getStatusCode() != CommonUtil.SC_OK) {
202                 logger.error(body);
203             }
204             result.setBody(body);
205             result.setStatusCode(res.getStatusLine().getStatusCode());
206             res.close();
207         } catch (ClientProtocolException e) {
208             logger.error(url + ":httpGetWithJSON connect faild", e);
209         } catch (IOException e) {
210             logger.error(url + ":httpGetWithJSON connect faild", e);
211         } finally {
212             try {
213                 httpClient.close();
214             } catch (IOException e) {
215                 logger.error(url + ":close  httpClient faild");
216             }
217         }
218
219         return result;
220
221     }
222
223     public static int httpGetStatus(String url) throws Exception {
224         int iStatus = 500;
225         CloseableHttpClient httpClient = HttpClients.createDefault();
226
227
228         HttpGet httpGet = new HttpGet(url);
229         RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();// 设置请求和传输超时时间
230         httpGet.setConfig(requestConfig);
231         httpGet.addHeader("Content-type", "application/json; charset=utf-8");
232         httpGet.setHeader("Accept", "application/json");
233         try {
234             CloseableHttpResponse res = httpClient.execute(httpGet);
235
236             iStatus = res.getStatusLine().getStatusCode();
237             res.close();
238         } catch (ClientProtocolException e) {
239             logger.error(url + " httpGet connect faild:" + e.getMessage());
240         } catch (IOException e) {
241             logger.error(url + " httpGet connect faild:" + e.getMessage());
242         } finally {
243             try {
244                 httpClient.close();
245             } catch (IOException e) {
246                 logger.error(url + " httpGet close faild:" + e.getMessage());
247             }
248         }
249
250         return iStatus;
251
252     }
253 }