163387f5ddc99fb4ec9fb9c170fa805bb89bda90
[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.NameValuePair;
22 import org.apache.http.client.ClientProtocolException;
23 import org.apache.http.client.config.RequestConfig;
24 import org.apache.http.client.methods.CloseableHttpResponse;
25 import org.apache.http.client.methods.HttpDelete;
26 import org.apache.http.client.methods.HttpGet;
27 import org.apache.http.client.methods.HttpPost;
28 import org.apache.http.client.utils.URLEncodedUtils;
29 import org.apache.http.entity.StringEntity;
30 import org.apache.http.impl.client.CloseableHttpClient;
31 import org.apache.http.impl.client.HttpClients;
32 import org.apache.http.message.BasicNameValuePair;
33 import org.apache.http.util.EntityUtils;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 public class HttpClientUtil {
38
39     private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
40
41     private static int connectionTimeOut = 2 * 1000;
42
43     public static HttpPost createHttpPost(String url, String params){
44         HttpPost httpPost = new HttpPost(url);
45         httpPost.addHeader("Content-type", "application/json; charset=utf-8");
46         httpPost.setHeader("Accept", "application/json");
47         httpPost.setEntity(new StringEntity(params, Charset.forName("UTF-8")));
48         return httpPost;
49      }
50     
51     public static HttpGet createHttpGet(String url){
52         HttpGet httpGet = new HttpGet(url);
53         httpGet.addHeader("Content-type", "application/json; charset=utf-8");
54         httpGet.setHeader("Accept", "application/json");
55         return httpGet;
56      }
57     
58     public static void closeHttpClient(CloseableHttpClient httpClient) {
59         if (httpClient != null) {
60             try {
61                 httpClient.close();
62             } catch (IOException e) {
63                 logger.error(httpClient + ":close  httpClient faild");
64             }
65         }
66     }
67     
68     public static void closeHttpResponse(CloseableHttpResponse response) {
69         if (response != null) {
70             try {
71                 response.close();
72             } catch (IOException e) {
73                 logger.error(response + ":close  response faild");
74             }
75         }
76     }
77     
78     public static CloseableHttpResponse httpGetWithResponse(String url) throws Exception {
79         CloseableHttpClient httpClient = HttpClients.createDefault();
80         HttpGet httpGet = new HttpGet(url);
81         httpGet.addHeader("Content-type", "application/json; charset=utf-8");
82         httpGet.setHeader("Accept", "application/json");
83         try {
84             return httpClient.execute(httpGet);         
85         } finally {
86             try {
87                 httpClient.close();
88             } catch (IOException e) {
89                 logger.error(url + ":close  httpClient faild");
90             }
91         }
92     }
93
94     public static void delete(String url, String parameter) throws Exception {
95         String result = null;
96         String baseUrl;
97         if (parameter != null) {
98             List<NameValuePair> params = new ArrayList<NameValuePair>();
99             params.add(new BasicNameValuePair("serviceName", parameter));
100             baseUrl = url + "?" + URLEncodedUtils.format(params, "UTF-8");
101         } else {
102             baseUrl = url;
103         }
104
105         CloseableHttpClient httpClient = HttpClients.createDefault();;
106         try {
107
108             HttpDelete httpDelete = new HttpDelete(baseUrl);
109             CloseableHttpResponse res = httpClient.execute(httpDelete);
110
111             if (res.getStatusLine().getStatusCode() != 200) {
112                 throw new Exception("delete fail");
113             }
114
115             res.close();
116         } catch (IOException e) {
117             String errorMsg = baseUrl + ":delete connect faild";
118         } finally {
119             try {
120                 httpClient.close();
121             } catch (IOException e) {
122                 String errorMsg = baseUrl + ":close  httpClient faild";
123             }
124         }
125
126     }
127
128
129     public static String httpGet(String url) {
130         String result = null;
131         CloseableHttpClient httpClient = HttpClients.createDefault();
132         HttpGet httpGet = new HttpGet(url);
133         httpGet.addHeader("Content-type", "application/json; charset=utf-8");
134         httpGet.setHeader("Accept", "application/json");
135         try {
136             CloseableHttpResponse res = httpClient.execute(httpGet);
137             result = EntityUtils.toString(res.getEntity());
138             if (res.getStatusLine().getStatusCode() != CommonUtil.SC_OK) {
139                 logger.error(result);
140             }
141             res.close();
142         } catch (ClientProtocolException e) {
143             logger.error(url + ":httpGetWithJSON connect faild");
144         } catch (IOException e) {
145             logger.error(url + ":httpGetWithJSON connect faild");
146         } finally {
147             try {
148                 httpClient.close();
149             } catch (IOException e) {
150                 logger.error(url + ":close  httpClient faild");
151             }
152         }
153
154         return result;
155
156     }
157
158     public static HttpGetResult httpGetStatusAndBody(String url) {
159         HttpGetResult result = new HttpGetResult();
160         String body = null;
161         CloseableHttpClient httpClient = HttpClients.createDefault();
162         HttpGet httpGet = new HttpGet(url);
163         httpGet.addHeader("Content-type", "application/json; charset=utf-8");
164         httpGet.setHeader("Accept", "application/json");
165
166         RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectionTimeOut).build();
167         httpGet.setConfig(requestConfig);
168
169         try {
170             CloseableHttpResponse res = httpClient.execute(httpGet);
171             body = EntityUtils.toString(res.getEntity());
172             if (res.getStatusLine().getStatusCode() != CommonUtil.SC_OK) {
173                 logger.error(body);
174             }
175             result.setBody(body);
176             result.setStatusCode(res.getStatusLine().getStatusCode());
177             res.close();
178         } catch (ClientProtocolException e) {
179             logger.error(url + ":httpGetWithJSON connect faild", e);
180         } catch (IOException e) {
181             logger.error(url + ":httpGetWithJSON connect faild", e);
182         } finally {
183             try {
184                 httpClient.close();
185             } catch (IOException e) {
186                 logger.error(url + ":close  httpClient faild");
187             }
188         }
189
190         return result;
191
192     }
193
194     public static int httpGetStatus(String url) throws Exception {
195         int iStatus = 500;
196         CloseableHttpClient httpClient = HttpClients.createDefault();
197
198
199         HttpGet httpGet = new HttpGet(url);
200         RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();// 设置请求和传输超时时间
201         httpGet.setConfig(requestConfig);
202         httpGet.addHeader("Content-type", "application/json; charset=utf-8");
203         httpGet.setHeader("Accept", "application/json");
204         try {
205             CloseableHttpResponse res = httpClient.execute(httpGet);
206
207             iStatus = res.getStatusLine().getStatusCode();
208             res.close();
209         } catch (ClientProtocolException e) {
210             logger.error(url + " httpGet connect faild:" + e.getMessage());
211         } catch (IOException e) {
212             logger.error(url + " httpGet connect faild:" + e.getMessage());
213         } finally {
214             try {
215                 httpClient.close();
216             } catch (IOException e) {
217                 logger.error(url + " httpGet close faild:" + e.getMessage());
218             }
219         }
220
221         return iStatus;
222
223     }
224 }