From a0fc599f93eeeeb678514492d72bce6b9f47c48e Mon Sep 17 00:00:00 2001 From: ChenJiaHe <763432473@qq.com> Date: 星期日, 26 十二月 2021 16:23:49 +0800 Subject: [PATCH] Merge branch 'master' of https://gitee.com/huoxiong/hx_common --- src/main/java/com/hx/util/HttpMethodUtil.java | 79 +++++++++++++++++++++++++++++++++++++++ 1 files changed, 79 insertions(+), 0 deletions(-) diff --git a/src/main/java/com/hx/util/HttpMethodUtil.java b/src/main/java/com/hx/util/HttpMethodUtil.java new file mode 100644 index 0000000..0ce4fea --- /dev/null +++ b/src/main/java/com/hx/util/HttpMethodUtil.java @@ -0,0 +1,79 @@ +package com.hx.util; + +import org.apache.commons.io.IOUtils; + +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.Map; + +/** + * http 宸ュ叿绫� + */ +public class HttpMethodUtil { + + /** 璇锋眰http鍗忚 鑾峰彇淇℃伅宸ュ叿 + * @param url 璇锋眰閾炬帴 + * @param data 璇锋眰鏁版嵁(body) + * @param keyValues form琛ㄥ崟鏁版嵁 key鍙傛暟鍚嶇О锛寁alue鍙傛暟鍊� + * @param header 璇锋眰澶� + * @param requestMethod 璇锋眰澶存柟娉曪紝榛樿POST + * @return + */ + public static String HttpURLUtilJson(String url, String data,Map<String,Object> keyValues,Map<String,String> header,String requestMethod) { + HttpURLConnection con = null; + URL u = null; + String wxMsgXml = null; + try { + StringBuilder dataP = new StringBuilder(); + if (keyValues != null && !keyValues.isEmpty()) { + for (Map.Entry<String, Object> entry : keyValues.entrySet()) { + dataP.append((String)entry.getKey()).append("="); + dataP.append(entry.getValue()); + dataP.append("&"); + } + System.out.println("dataP:"+dataP.toString()); + dataP.deleteCharAt(dataP.length() - 1); + url = url+"?"+dataP; + } + + if(StringUtils.isEmpty(requestMethod)){ + requestMethod = "POST"; + } + u = new URL(url); + con = (HttpURLConnection) u.openConnection(); + con.setRequestMethod(requestMethod); + con.setDoOutput(true); + con.setDoInput(true); + con.setUseCaches(false); + con.setReadTimeout(5000); + con.setRequestProperty("Charset", "UTF-8"); + con.setRequestProperty("Content-Type", "application/json"); + if(header != null){ + for (Map.Entry<String, String> entry : header.entrySet()) { + con.setRequestProperty(entry.getKey(),entry.getValue()); + } + } + + if (data != null) { + OutputStream os = con.getOutputStream(); + os.write(data.getBytes("utf-8")); + } + + if (con.getResponseCode() != 200){ + throw new RuntimeException("璇锋眰url澶辫触:"+con.getResponseCode()); + } + // 璇诲彇杩斿洖鍐呭 + wxMsgXml = IOUtils.toString(con.getInputStream(), "utf-8"); + // //System.out.println("HttpURLUtil:"+wxMsgXml); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (con != null) { + con.disconnect(); + } + } + return wxMsgXml; + } + +} -- Gitblit v1.8.0