106653b62ebaa4eed3c945ac978c6444a3fb0936
[msb/discovery.git] / sdclient / discovery-service / src / main / java / org / onap / msb / sdclient / 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.sdclient.wrapper.util;
15
16 import java.io.IOException;
17 import java.math.BigInteger;
18 import java.nio.charset.Charset;
19 import java.util.ArrayList;
20 import java.util.List;
21
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.HttpGet;
28 import org.apache.http.client.methods.HttpPost;
29 import org.apache.http.client.methods.HttpPut;
30 import org.apache.http.client.utils.URLEncodedUtils;
31 import org.apache.http.entity.StringEntity;
32 import org.apache.http.impl.client.CloseableHttpClient;
33 import org.apache.http.impl.client.HttpClients;
34 import org.apache.http.message.BasicNameValuePair;
35 import org.apache.http.util.EntityUtils;
36 import org.onap.msb.sdclient.core.ConsulResponse;
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     public static int httpPutWithJSON(String url, String params) {
45         int result = 0;
46         CloseableHttpClient httpClient = HttpClients.createDefault();
47         HttpPut httpPut = new HttpPut(url);
48         httpPut.addHeader("Content-type", "application/json; charset=utf-8");
49         httpPut.setHeader("Accept", "application/json");
50         httpPut.setEntity(new StringEntity(params, Charset.forName("UTF-8")));
51         try {
52             CloseableHttpResponse res = httpClient.execute(httpPut);
53             result = res.getStatusLine().getStatusCode();
54             if (res.getStatusLine().getStatusCode() != 200) {
55                 logger.error(String.valueOf(result));
56             }
57             res.close();
58         } catch (IOException e) {
59             String errorMsg = url + ":httpPutWithJSON connect faild";
60         } finally {
61             try {
62                 httpClient.close();
63             } catch (IOException e) {
64                 String errorMsg = url + ":close  httpClient faild";
65             }
66         }
67
68         return result;
69
70     }
71
72     public static int httpPostWithJSON(String url, String params) {
73         int result = 0;
74         CloseableHttpClient httpClient = HttpClients.createDefault();
75         HttpPost httpPost = new HttpPost(url);
76         httpPost.addHeader("Content-type", "application/json; charset=utf-8");
77         httpPost.setHeader("Accept", "application/json");
78         httpPost.setEntity(new StringEntity(params, Charset.forName("UTF-8")));
79         try {
80             CloseableHttpResponse res = httpClient.execute(httpPost);
81             result = res.getStatusLine().getStatusCode();
82             if (res.getStatusLine().getStatusCode() != 200) {
83                 logger.error(String.valueOf(result));
84             }
85             res.close();
86         } catch (IOException e) {
87             String errorMsg = url + ":httpPostWithJSON connect faild";
88         } finally {
89             try {
90                 httpClient.close();
91             } catch (IOException e) {
92                 String errorMsg = url + ":close  httpClient faild";
93             }
94         }
95
96         return result;
97
98     }
99
100     public static void delete(String url, String parameter) throws Exception {
101         String result = null;
102         String baseUrl;
103         if (parameter != null) {
104             List<NameValuePair> params = new ArrayList<NameValuePair>();
105             params.add(new BasicNameValuePair("serviceName", parameter));
106             baseUrl = url + "?" + URLEncodedUtils.format(params, "UTF-8");
107         } else {
108             baseUrl = url;
109         }
110
111         CloseableHttpClient httpClient = HttpClients.createDefault();;
112         try {
113
114             HttpDelete httpDelete = new HttpDelete(baseUrl);
115             CloseableHttpResponse res = httpClient.execute(httpDelete);
116
117             if (res.getStatusLine().getStatusCode() != 200) {
118                 throw new Exception("delete fail");
119             }
120
121             res.close();
122         } catch (IOException e) {
123             String errorMsg = baseUrl + ":delete connect faild";
124         } finally {
125             try {
126                 httpClient.close();
127             } catch (IOException e) {
128                 String errorMsg = baseUrl + ":close  httpClient faild";
129             }
130         }
131
132     }
133
134     public static String httpGet(String url) {
135         String result = null;
136         CloseableHttpClient httpClient = HttpClients.createDefault();
137         HttpGet httpGet = new HttpGet(url);
138         httpGet.addHeader("Content-type", "application/json; charset=utf-8");
139         httpGet.setHeader("Accept", "application/json");
140         try {
141             CloseableHttpResponse res = httpClient.execute(httpGet);
142
143             res.getLastHeader("X-Consul-Index");
144             result = EntityUtils.toString(res.getEntity());
145             if (res.getStatusLine().getStatusCode() != 200) {
146                 logger.error(result);
147             }
148             res.close();
149         } catch (ClientProtocolException e) {
150             String errorMsg = url + ":httpGetWithJSON connect faild";
151             logger.error(errorMsg);
152         } catch (IOException e) {
153             String errorMsg = url + ":httpGetWithJSON connect faild";
154             logger.error(errorMsg);
155         } finally {
156             try {
157                 httpClient.close();
158             } catch (IOException e) {
159                 String errorMsg = url + ":close  httpClient faild";
160                 logger.error(errorMsg);
161             }
162         }
163
164         return result;
165
166     }
167
168     @SuppressWarnings("unchecked")
169     public static <T> ConsulResponse<T> httpWaitGet(String url) {
170         CloseableHttpClient httpClient = HttpClients.createDefault();
171         HttpGet httpGet = new HttpGet(url);
172         httpGet.addHeader("Content-type", "application/json; charset=utf-8");
173         httpGet.setHeader("Accept", "application/json");
174         try {
175             CloseableHttpResponse res = httpClient.execute(httpGet);
176             String result = EntityUtils.toString(res.getEntity());
177
178             if (res.getStatusLine().getStatusCode() != 200) {
179                 logger.error(result);
180             } else {
181                 String indexHeaderValue = res.getLastHeader("X-Consul-Index").getValue();
182                 BigInteger index = new BigInteger(indexHeaderValue);
183
184                 return new ConsulResponse<T>((T) result, index);
185
186             }
187
188             res.close();
189         } catch (ClientProtocolException e) {
190             String errorMsg = url + ":httpGetWithJSON connect faild " + e.getMessage();
191             logger.error(errorMsg);
192         } catch (IOException e) {
193             String errorMsg = url + ":httpGetWithJSON connect faild " + e.getMessage();
194             logger.error(errorMsg);
195         } finally {
196             try {
197                 httpClient.close();
198             } catch (IOException e) {
199                 String errorMsg = url + ":close  httpClient faild " + e.getMessage();
200                 logger.error(errorMsg);
201             }
202         }
203
204         return null;
205
206     }
207
208     public static int httpGetStatus(String url) throws Exception {
209         int iStatus = 500;
210         CloseableHttpClient httpClient = HttpClients.createDefault();
211
212         HttpGet httpGet = new HttpGet(url);
213         RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();// 设置请求和传输超时时间
214         httpGet.setConfig(requestConfig);
215         httpGet.addHeader("Content-type", "application/json; charset=utf-8");
216         httpGet.setHeader("Accept", "application/json");
217         try {
218             CloseableHttpResponse res = httpClient.execute(httpGet);
219
220             iStatus = res.getStatusLine().getStatusCode();
221             res.close();
222         } catch (ClientProtocolException e) {
223             logger.error(url + " httpGet connect faild:" + e.getMessage());
224         } catch (IOException e) {
225             logger.error(url + " httpGet connect faild:" + e.getMessage());
226         } finally {
227             try {
228                 httpClient.close();
229             } catch (IOException e) {
230                 logger.error(url + " httpGet close faild:" + e.getMessage());
231             }
232         }
233
234         return iStatus;
235
236     }
237
238 }