modify copyright year
[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");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16 package org.onap.msb.sdclient.wrapper.util;
17
18 import java.io.IOException;
19 import java.math.BigInteger;
20 import java.nio.charset.Charset;
21 import java.util.ArrayList;
22 import java.util.List;
23
24 import org.apache.http.NameValuePair;
25 import org.apache.http.client.ClientProtocolException;
26 import org.apache.http.client.config.RequestConfig;
27 import org.apache.http.client.methods.CloseableHttpResponse;
28 import org.apache.http.client.methods.HttpDelete;
29 import org.apache.http.client.methods.HttpGet;
30 import org.apache.http.client.methods.HttpPost;
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.onap.msb.sdclient.core.ConsulResponse;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 public class HttpClientUtil {
42
43         private static final Logger logger = LoggerFactory
44                         .getLogger(HttpClientUtil.class);
45
46         public static int httpPostWithJSON(String url, String params) {
47                 int result = 0;
48                 CloseableHttpClient httpClient = HttpClients.createDefault();
49                 HttpPost httpPost = new HttpPost(url);
50                 httpPost.addHeader("Content-type", "application/json; charset=utf-8");
51                 httpPost.setHeader("Accept", "application/json");
52                 httpPost.setEntity(new StringEntity(params, Charset.forName("UTF-8")));
53                 try {
54                         CloseableHttpResponse res = httpClient.execute(httpPost);
55                         result = res.getStatusLine().getStatusCode();
56                         if (res.getStatusLine().getStatusCode() != 200) {
57                                 logger.error(String.valueOf(result));
58                         }
59                         res.close();
60                 } catch (IOException e) {
61                         String errorMsg = url + ":httpPostWithJSON connect faild";
62                 } finally {
63                         try {
64                                 httpClient.close();
65                         } catch (IOException e) {
66                                 String errorMsg = url + ":close  httpClient faild";
67                         }
68                 }
69
70                 return result;
71
72         }
73
74         public static void delete(String url, String parameter) throws Exception {
75                 String result = null;
76                 String baseUrl;
77                 if (parameter != null) {
78                         List<NameValuePair> params = new ArrayList<NameValuePair>();
79                         params.add(new BasicNameValuePair("serviceName", parameter));
80                         baseUrl = url + "?" + URLEncodedUtils.format(params, "UTF-8");
81                 } else {
82                         baseUrl = url;
83                 }
84
85                 CloseableHttpClient httpClient = HttpClients.createDefault();
86                 ;
87                 try {
88
89                         HttpDelete httpDelete = new HttpDelete(baseUrl);
90                         CloseableHttpResponse res = httpClient.execute(httpDelete);
91
92                         if (res.getStatusLine().getStatusCode() != 200) {
93                                 throw new Exception("delete fail");
94                         }
95
96                         res.close();
97                 } catch (IOException e) {
98                         String errorMsg = baseUrl + ":delete connect faild";
99                 } finally {
100                         try {
101                                 httpClient.close();
102                         } catch (IOException e) {
103                                 String errorMsg = baseUrl + ":close  httpClient faild";
104                         }
105                 }
106
107         }
108
109         public static String httpGet(String url) {
110                 String result = null;
111                 CloseableHttpClient httpClient = HttpClients.createDefault();
112                 HttpGet httpGet = new HttpGet(url);
113                 httpGet.addHeader("Content-type", "application/json; charset=utf-8");
114                 httpGet.setHeader("Accept", "application/json");
115                 try {
116                         CloseableHttpResponse res = httpClient.execute(httpGet);
117
118                         res.getLastHeader("X-Consul-Index");
119                         result = EntityUtils.toString(res.getEntity());
120                         if (res.getStatusLine().getStatusCode() != 200) {
121                                 logger.error(result);
122                         }
123                         res.close();
124                 } catch (ClientProtocolException e) {
125                         String errorMsg = url + ":httpGetWithJSON connect faild";
126                         logger.error(errorMsg);
127                 } catch (IOException e) {
128                         String errorMsg = url + ":httpGetWithJSON connect faild";
129                         logger.error(errorMsg);
130                 } finally {
131                         try {
132                                 httpClient.close();
133                         } catch (IOException e) {
134                                 String errorMsg = url + ":close  httpClient faild";
135                                 logger.error(errorMsg);
136                         }
137                 }
138
139                 return result;
140
141         }
142
143         @SuppressWarnings("unchecked")
144         public static <T> ConsulResponse<T> httpWaitGet(String url) {
145                 CloseableHttpClient httpClient = HttpClients.createDefault();
146                 HttpGet httpGet = new HttpGet(url);
147                 httpGet.addHeader("Content-type", "application/json; charset=utf-8");
148                 httpGet.setHeader("Accept", "application/json");
149                 try {
150                         CloseableHttpResponse res = httpClient.execute(httpGet);
151                         String result = EntityUtils.toString(res.getEntity());
152
153                         if (res.getStatusLine().getStatusCode() != 200) {
154                                 logger.error(result);
155                         } else {
156                                 String indexHeaderValue = res.getLastHeader("X-Consul-Index")
157                                                 .getValue();
158                                 BigInteger index = new BigInteger(indexHeaderValue);
159
160                                 return new ConsulResponse<T>((T) result, index);
161
162                         }
163
164                         res.close();
165                 } catch (ClientProtocolException e) {
166                         String errorMsg = url + ":httpGetWithJSON connect faild "
167                                         + e.getMessage();
168                         logger.error(errorMsg);
169                 } catch (IOException e) {
170                         String errorMsg = url + ":httpGetWithJSON connect faild "
171                                         + e.getMessage();
172                         logger.error(errorMsg);
173                 } finally {
174                         try {
175                                 httpClient.close();
176                         } catch (IOException e) {
177                                 String errorMsg = url + ":close  httpClient faild "
178                                                 + e.getMessage();
179                                 logger.error(errorMsg);
180                         }
181                 }
182
183                 return null;
184
185         }
186
187         public static int httpGetStatus(String url) throws Exception {
188                 int iStatus = 500;
189                 CloseableHttpClient httpClient = HttpClients.createDefault();
190
191                 HttpGet httpGet = new HttpGet(url);
192                 RequestConfig requestConfig = RequestConfig.custom()
193                                 .setSocketTimeout(10000).setConnectTimeout(10000).build();// 设置请求和传输超时时间
194                 httpGet.setConfig(requestConfig);
195                 httpGet.addHeader("Content-type", "application/json; charset=utf-8");
196                 httpGet.setHeader("Accept", "application/json");
197                 try {
198                         CloseableHttpResponse res = httpClient.execute(httpGet);
199
200                         iStatus = res.getStatusLine().getStatusCode();
201                         res.close();
202                 } catch (ClientProtocolException e) {
203                         logger.error(url + " httpGet connect faild:" + e.getMessage());
204                 } catch (IOException e) {
205                         logger.error(url + " httpGet connect faild:" + e.getMessage());
206                 } finally {
207                         try {
208                                 httpClient.close();
209                         } catch (IOException e) {
210                                 logger.error(url + " httpGet close faild:" + e.getMessage());
211                         }
212                 }
213
214                 return iStatus;
215
216         }
217
218 }