package com.awifi.capacity.analysis.push.util; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.net.HttpURLConnection; import java.net.URL; import java.util.Map; /** * @Description: httpclient * @Author: hw * @CreateDate: 2019/6/4 */ public class HttpClientUtil { /** * 日志 */ private static final Logger LOG = LoggerFactory.getLogger(HttpClientUtil.class); /** * 发送HttpPost请求 * @param uri 服务地址 * @param paramMap * @return * @throws Exception * @author hw * @date 2019/3/7 16:19 */ public static String jsonPost(String uri, Map<String, String> paramMap)throws Exception{ LOG.info("HTTP POST请求, uri={}, param={}", uri, JSON.toJSONString(paramMap)); //访问准备 URL url = new URL(uri); byte[] postDataBytes = JSON.toJSONString(paramMap).getBytes("UTF-8"); Reader in = null; try { HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length)); conn.setDoOutput(true); conn.setConnectTimeout(20*1000); conn.setReadTimeout(20*1000); conn.getOutputStream().write(postDataBytes);
int code = conn.getResponseCode(); if (code == 200) { // 得到网络返回的正确输入流 in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); } else { // 得到网络返回的错误输入流 in = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8")); } StringBuilder sb = new StringBuilder(); for (int c; (c = in.read()) >= 0;) { sb.append((char) c); } String response = sb.toString(); LOG.info(response); return response; }catch (Exception e){ LOG.error("执行HTTP POST异常, uri={}, 参数为:{}, 异常消息:{}", uri, JSON.toJSONString(paramMap), StringUtil.getExceptionStackTrace(e)); }finally { try { if(in!=null) { in.close(); } } catch (IOException e) { LOG.error("执行HTTP POST关闭Response流异常,uri={}, param={}, 异常消息:{}", uri, JSON.toJSONString(paramMap), StringUtil.getExceptionStackTrace(e)); } } return null; } }