diff options
author | shentao999 <shentao@chinamobile.com> | 2019-08-22 17:55:22 +0800 |
---|---|---|
committer | shentao999 <shentao@chinamobile.com> | 2019-08-22 17:55:24 +0800 |
commit | 54df8f33080cec390e2d90be628c3f39b2ea1c6e (patch) | |
tree | 8658b3da51c38760c32f228041856c02b46a18ea | |
parent | 589edee5aa87f12749e87f5d7ef19fe143cd4338 (diff) |
Add uui-server common GET/DELETE/POST/PUT method
Change-Id: I02baca206f7acfb79f1dff5fef3180342f388031
Issue-ID: USECASEUI-307
Signed-off-by: shentao999 <shentao@chinamobile.com>
-rw-r--r-- | server/src/main/java/org/onap/usecaseui/server/util/HttpUtil.java | 445 |
1 files changed, 346 insertions, 99 deletions
diff --git a/server/src/main/java/org/onap/usecaseui/server/util/HttpUtil.java b/server/src/main/java/org/onap/usecaseui/server/util/HttpUtil.java index 07514660..0763f33c 100644 --- a/server/src/main/java/org/onap/usecaseui/server/util/HttpUtil.java +++ b/server/src/main/java/org/onap/usecaseui/server/util/HttpUtil.java @@ -17,134 +17,381 @@ package org.onap.usecaseui.server.util; import java.io.BufferedReader; import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.net.URL; -import java.net.URLConnection; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.Set; -import com.google.common.base.Throwables; +import org.apache.http.HttpStatus; +import org.apache.http.NameValuePair; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.*; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; +import org.onap.usecaseui.server.bean.HttpResponseResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.servlet.http.HttpServletRequest; + +import static org.onap.usecaseui.server.constant.CommonConstant.BLANK; +import static org.onap.usecaseui.server.constant.CommonConstant.ENCODING_UTF8; + public class HttpUtil { - - private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class); + private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class); + /** - * 向指定URL发送GET方法的请求 - * + * common POST method for REST API calling by using map request body + * * @param url - * 发送请求的URL - * @param param - * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 - * @return URL 所代表远程资源的响应结果 + * @param headerMap + * @param requestBodyMap + * @return HttpResponseResult */ - - private HttpUtil() { - - } - public static String sendGet(String url, String param) { - String result = ""; - BufferedReader in = null; + public static HttpResponseResult sendPostRequestByMap( + String url, + Map<String, String> headerMap, + Map<String, String> requestBodyMap) { + logger.info("[" + url + "]" + " API POST calling is starting......"); + HttpResponseResult responseResult = new HttpResponseResult(HttpStatus.SC_NOT_FOUND, BLANK); + CloseableHttpClient httpClient = HttpClients.createDefault(); + try { - String urlNameString = url + "?" + param; - URL realUrl = new URL(urlNameString); - // 打开和URL之间的连接 - URLConnection connection = realUrl.openConnection(); - // 设置通用的请求属性 - connection.setRequestProperty("accept", "*/*"); - connection.setRequestProperty("connection", "Keep-Alive"); - connection.setRequestProperty("user-agent", - "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); - // 建立实际的连接 - connection.connect(); - // 获取所有响应头字段 - Map<String, List<String>> map = connection.getHeaderFields(); - // 遍历所有的响应头字段 - for (String key : map.keySet()) { - logger.error(key , "{} {}--->" , map.get(key)); + // set request url and header for API calling + HttpPost httpPost = new HttpPost(url); + setHeader(httpPost, headerMap); + + // set request body for API calling + httpPost.setEntity(setBodyByMap(requestBodyMap)); + + // execute API calling and set response + CloseableHttpResponse response = httpClient.execute(httpPost); + setResponse(response, responseResult); + } catch (ClientProtocolException cpe) { + logger.error(cpe.toString()); + cpe.printStackTrace(); + } catch (IOException ioe) { + logger.error(ioe.toString()); + ioe.printStackTrace(); + } catch (Exception e) { + logger.error(e.toString()); + e.printStackTrace(); + } finally { + try { + httpClient.close(); + } catch (Exception e) { + logger.error(e.toString()); + e.printStackTrace(); } - // 定义 BufferedReader输入流来读取URL的响应 - in = new BufferedReader(new InputStreamReader( - connection.getInputStream())); - String line; - while ((line = in.readLine()) != null) { - result += line; + } + + logger.info("[" + url + "]" + " API POST calling has finished!"); + return responseResult; + } + + /** + * common POST method for REST API calling by using json request body + * + * @param url + * @param headerMap + * @param requestBodyJson + * @return HttpResponseResult + */ + public static HttpResponseResult sendPostRequestByJson( + String url, + Map<String, String> headerMap, + String requestBodyJson) { + logger.info("[" + url + "]" + " API POST calling is starting......"); + HttpResponseResult responseResult = new HttpResponseResult(HttpStatus.SC_NOT_FOUND, BLANK); + CloseableHttpClient httpClient = HttpClients.createDefault(); + + try { + // set request url and header for API calling + HttpPost httpPost = new HttpPost(url); + setHeader(httpPost, headerMap); + + // set request body for API calling + httpPost.setEntity(setBodyByJson(requestBodyJson)); + + // execute API calling and return response + CloseableHttpResponse response = httpClient.execute(httpPost); + setResponse(response, responseResult); + } catch (ClientProtocolException cpe) { + logger.error(cpe.toString()); + cpe.printStackTrace(); + } catch (IOException ioe) { + logger.error(ioe.toString()); + ioe.printStackTrace(); + } catch (Exception e) { + logger.error(e.toString()); + e.printStackTrace(); + } finally { + try { + httpClient.close(); + } catch (Exception e) { + logger.error(e.toString()); + e.printStackTrace(); } + } + + logger.info("[" + url + "]" + " API POST calling has finished!"); + return responseResult; + } + + /** + * common GET method for REST API calling + * + * @param url + * @param headerMap + * @return HttpResponseResult + */ + public HttpResponseResult sendGetRequest( + String url, + Map<String, String> headerMap) { + logger.info("[" + url + "]" + " API GET calling is starting......"); + HttpResponseResult responseResult = new HttpResponseResult(HttpStatus.SC_NOT_FOUND, BLANK); + CloseableHttpClient httpClient = HttpClients.createDefault(); + + try { + // set request url and header for API calling + HttpGet httpGet = new HttpGet(url); + setHeader(httpGet, headerMap); + + // execute API calling and return response + CloseableHttpResponse response = httpClient.execute(httpGet); + setResponse(response, responseResult); + } catch (ClientProtocolException cpe) { + logger.error(cpe.toString()); + cpe.printStackTrace(); + } catch (IOException ioe) { + logger.error(ioe.toString()); + ioe.printStackTrace(); } catch (Exception e) { - logger.error("发送GET请求出现异常!" + e); - logger.error("发送GET请求出现异常!" + Throwables.getStackTraceAsString(e)); + logger.error(e.toString()); + e.printStackTrace(); + } finally { + try { + httpClient.close(); + } catch (Exception e) { + logger.error(e.toString()); + e.printStackTrace(); + } } - // 使用finally块来关闭输入流 - finally { + + logger.info("[" + url + "]" + " API GET calling has finished!"); + return responseResult; + } + + /** + * common PUT method for REST API calling by using map request body + * + * @param url AAAAA + * @param headerMap AAAAA + * @param requestBodyMap AAAAA + * @return HttpResponseResult + */ + public static HttpResponseResult sendPutRequestByMap( + String url, + Map<String, String> headerMap, + Map<String, String> requestBodyMap) { + logger.info("[" + url + "]" + " API PUT calling is starting......"); + HttpResponseResult responseResult = new HttpResponseResult(HttpStatus.SC_NOT_FOUND, BLANK); + CloseableHttpClient httpClient = HttpClients.createDefault(); + + try { + // set request url and header for API calling + HttpPut httpPut = new HttpPut(url); + setHeader(httpPut, headerMap); + + // set request body for API calling + httpPut.setEntity(setBodyByMap(requestBodyMap)); + + // execute API calling and set response + CloseableHttpResponse response = httpClient.execute(httpPut); + setResponse(response, responseResult); + } catch (ClientProtocolException cpe) { + logger.error(cpe.toString()); + cpe.printStackTrace(); + } catch (IOException ioe) { + logger.error(ioe.toString()); + ioe.printStackTrace(); + } catch (Exception e) { + logger.error(e.toString()); + e.printStackTrace(); + } finally { try { - if (in != null) { - in.close(); - } - } catch (Exception e2) { - logger.error("Exception occured while closing the connection {}" + Throwables.getStackTraceAsString(e2)); + httpClient.close(); + } catch (Exception e) { + logger.error(e.toString()); + e.printStackTrace(); } } - return result; + + logger.info("[" + url + "]" + " API PUT calling has finished!"); + return responseResult; } /** - * 向指定 URL 发送POST方法的请求 - * + * common PUT method for REST API calling by using json request body + * * @param url - * 发送请求的 URL - * @param param - * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 - * @return 所代表远程资源的响应结果 + * @param headerMap + * @param requestBodyJson + * @return HttpResponseResult */ - public static String sendPost(String url, String param) { - PrintWriter out = null; - BufferedReader in = null; - String result = ""; + public static HttpResponseResult sendPutRequestByJson( + String url, + Map<String, String> headerMap, + String requestBodyJson) { + logger.info("[" + url + "]" + " API PUT calling is starting......"); + HttpResponseResult responseResult = new HttpResponseResult(HttpStatus.SC_NOT_FOUND, BLANK); + CloseableHttpClient httpClient = HttpClients.createDefault(); + try { - URL realUrl = new URL(url); - // 打开和URL之间的连接 - URLConnection conn = realUrl.openConnection(); - // 设置通用的请求属性 - conn.setRequestProperty("accept", "*/*"); - conn.setRequestProperty("connection", "Keep-Alive"); - conn.setRequestProperty("user-agent", - "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); - // 发送POST请求必须设置如下两行 - conn.setDoOutput(true); - conn.setDoInput(true); - // 获取URLConnection对象对应的输出流 - out = new PrintWriter(conn.getOutputStream()); - // 发送请求参数 - out.print(param); - // flush输出流的缓冲 - out.flush(); - // 定义BufferedReader输入流来读取URL的响应 - in = new BufferedReader( - new InputStreamReader(conn.getInputStream())); - String line; - while ((line = in.readLine()) != null) { - result += line; + // set request url and header for API calling + HttpPut httpPut = new HttpPut(url); + setHeader(httpPut, headerMap); + + // set request body for API calling + httpPut.setEntity(setBodyByJson(requestBodyJson)); + + // execute API calling and return response + CloseableHttpResponse response = httpClient.execute(httpPut); + setResponse(response, responseResult); + } catch (ClientProtocolException cpe) { + logger.error(cpe.toString()); + cpe.printStackTrace(); + } catch (IOException ioe) { + logger.error(ioe.toString()); + ioe.printStackTrace(); + } catch (Exception e) { + logger.error(e.toString()); + e.printStackTrace(); + } finally { + try { + httpClient.close(); + } catch (Exception e) { + logger.error(e.toString()); + e.printStackTrace(); } + } + + logger.info("[" + url + "]" + " API PUT calling has finished!"); + return responseResult; + } + + /** + * common DELETE method for REST API calling + * + * @param url + * @param headerMap + * @return HttpResponseResult + */ + public HttpResponseResult sendDeleteRequest( + String url, + Map<String, String> headerMap) { + logger.info("[" + url + "]" + " API DELETE calling is starting......"); + HttpResponseResult responseResult = new HttpResponseResult(HttpStatus.SC_NOT_FOUND, BLANK); + CloseableHttpClient httpClient = HttpClients.createDefault(); + + try { + // set request url and header for API calling + HttpDelete httpDelete = new HttpDelete(url); + setHeader(httpDelete, headerMap); + + // execute API calling and return response + CloseableHttpResponse response = httpClient.execute(httpDelete); + setResponse(response, responseResult); + } catch (ClientProtocolException cpe) { + logger.error(cpe.toString()); + cpe.printStackTrace(); + } catch (IOException ioe) { + logger.error(ioe.toString()); + ioe.printStackTrace(); } catch (Exception e) { - logger.error("发送 POST 请求出现异常!"+e); - logger.error("发送 POST 请求出现异常!"+Throwables.getStackTraceAsString(e)); + logger.error(e.toString()); + e.printStackTrace(); + } finally { + try { + httpClient.close(); + } catch (Exception e) { + logger.error(e.toString()); + e.printStackTrace(); + } } - //使用finally块来关闭输出流、输入流 - finally{ - try{ - if(out!=null){ - out.close(); - } - if(in!=null){ - in.close(); + + logger.info("[" + url + "]" + " API DELETE calling has finished!"); + return responseResult; + } + + /** + * get string content from request body + * + * @param request + * @return String + */ + public static String ReadAsChars(HttpServletRequest request) { + BufferedReader br = null; + StringBuilder sb = new StringBuilder(BLANK); + + try { + br = request.getReader(); + String tempString; + while ((tempString = br.readLine()) != null) { + sb.append(tempString); + } + br.close(); + } catch (IOException ioe) { + ioe.printStackTrace(); + } finally { + if (null != br) { + try { + br.close(); + } catch (IOException ioe) { + ioe.printStackTrace(); } } - catch(IOException ex){ - logger.error("{}",ex.getMessage()); + } + + return sb.toString(); + } + + private static void setHeader(HttpRequestBase request, Map<String, String> headerMap) { + if (headerMap != null) { + Set<String> keySet = headerMap.keySet(); + for (String key : keySet) { + request.addHeader(key, headerMap.get(key)); } } - return result; - } + } + + private static UrlEncodedFormEntity setBodyByMap(Map<String, String> requestBodyMap) throws UnsupportedEncodingException { + List<NameValuePair> nvp = new ArrayList<>(); + if (requestBodyMap != null) { + for (Map.Entry<String, String> entry : requestBodyMap.entrySet()) { + nvp.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); + } + } + return new UrlEncodedFormEntity(nvp, ENCODING_UTF8); + } + + private static StringEntity setBodyByJson(String requestBodyJson) { + StringEntity se = new StringEntity(requestBodyJson, ContentType.APPLICATION_JSON); + se.setContentEncoding(ENCODING_UTF8); + return se; + } + + private static void setResponse(CloseableHttpResponse response, HttpResponseResult responseResult) throws IOException { + if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { + responseResult.setResultContent(EntityUtils.toString(response.getEntity(), ENCODING_UTF8)); + } + responseResult.setResultCode(response.getStatusLine().getStatusCode()); + response.close(); + } } |