package com.kingdee.eas.custom.wamke.syncdata.utils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLConnection; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicHeader; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; import com.kingdee.bos.BOSException; import com.kingdee.eas.custom.constants.Constants; import com.kingdee.eas.custom.utils.ObjectUtils; import com.kingdee.eas.custom.utils.StringUtils; public class HttpUtils { private static Logger logger = Logger.getLogger("com.kingdee.eas.custom.wamke.utils.HttpUtils"); private static final int MAX_CONNECT_TIMEOUT = 10000; private static final int MAX_SOCKET_TIMEOUT = 60000; public static String sendGet(String url, String param){ return sendGet(url,param, "UTF_8"); } /** * 向指定 URL 发送GET方法的请求 * * @param url 发送请求的 URL * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @param contentType 编码类型 * @return 所代表远程资源的响应结果 * @throws BOSException */ public static String sendGet(String url, String param, String contentType) { StringBuilder result = new StringBuilder(); BufferedReader in = null; try { String urlNameString = (param!=null&¶m!="") ? url + "?" + param : url; URL realUrl = new URL(urlNameString); System.out.println("请求URL:"+realUrl); 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(); in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType)); String line; while ((line = in.readLine()) != null) { result.append(line); } } catch (Exception e) { logger.error(e.getMessage()); e.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (Exception ex) { logger.error(ex.getMessage()); } } return result.toString(); } /** * @param url * @param paramMap * @param contentType * @return */ public static String sendGet(String url, Map paramMap, String contentType) { StringBuilder sb = new StringBuilder(); if (null != paramMap && !paramMap.isEmpty()) { for (Map.Entry entry : paramMap.entrySet()) { if (sb.length() > 0) { sb.append("&"); } sb.append(entry.getKey()).append("=").append(entry.getValue()); } } if (StringUtils.isBlank(contentType)) { contentType = Constants.UTF8; } return sendGet(url, sb.toString(), contentType); } /** * 发送post请求 * @param uri * @param paramStr * @return */ public static String sendPost(String uri, String paramStr){ return sendPost(uri,paramStr,null); } /** * 发送post请求 * @param uri 请求地址 * @param paramStr 请求的JSON数据 * @param token 头部token * @return */ public static String sendPost(String uri, String paramStr, String token) { // 创建默认的httpClient实例. CloseableHttpClient httpclient = HttpClients.createDefault(); // 创建httpPost HttpPost httppost = new HttpPost(uri); // 创建参数队列 StringEntity uefEntity = null; String result = null; try { String reqJson = paramStr; // JSON.toJSONString(paramsMap); uefEntity = new StringEntity(reqJson, "UTF-8"); uefEntity.setContentType("text/json"); uefEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); httppost.setEntity(uefEntity); httppost.setHeader("Content-Type", "application/json"); if (ObjectUtils.isNotEmpty(token)) { httppost.setHeader("Authorization", token); } CloseableHttpResponse response = httpclient.execute(httppost); if (response.getStatusLine().getStatusCode() != 200) { String msg = "http请求处理异常."; msg += response.toString(); } try { HttpEntity entity = response.getEntity(); if (entity != null) { result = EntityUtils.toString(entity, "UTF-8"); } } finally { response.close(); } } catch (ClientProtocolException e) { logger.error(e.getMessage(), e); } catch (UnsupportedEncodingException e1) { logger.error(e1.getMessage(), e1); } catch (IOException e) { logger.error(e.getMessage(), e); } finally { // 关闭连接,释放资源 try { httpclient.close(); } catch (IOException e) { logger.error(e.getMessage(), e); } } return result; } /** * XML/JSON入参的HTTP交互 * @param url * @param contentType * @param headers * @param content XML/JSON数据 * @param httpConnectTimeout * @param httpSocketTimeout * @param httpSocketTimeout * @return outLogs 输出全量日志 * @Author KangLG<2 0 2 2 年8月11日> */ public static String postRemote(String url, String contentType, Map headers, String content, int httpConnectTimeout, int httpSocketTimeout, boolean outLogs) { String result = null; try { HttpPost post = new HttpPost(url.trim()); post.setEntity(new StringEntity(content, "UTF-8")); post.setHeader("Content-Type", null != contentType ? contentType : "application/json"); if (null != headers && !headers.isEmpty()) { for (Map.Entry item : headers.entrySet()) { post.setHeader(item.getKey(), item.getValue()); } } //设置请求和传输超时时间 // RequestConfig requestConfig = RequestConfig.custom() // .setConnectTimeout(httpConnectTimeout > 0 ? httpConnectTimeout : MAX_CONNECT_TIMEOUT) // .setSocketTimeout(httpSocketTimeout > 0 ? httpSocketTimeout : MAX_SOCKET_TIMEOUT) // .build(); // post. (requestConfig); CloseableHttpClient httpclient = HttpClientBuilder.create().build(); CloseableHttpResponse response = httpclient.execute(post); HttpEntity responseEntity = response.getEntity(); System.out.println(String.format("[%s]响应信息: ContentType=%s, 状态=%s", url, null != responseEntity ? responseEntity.getContentType() : "null", response.getStatusLine())); if (null == responseEntity) { return null; } result = EntityUtils.toString(responseEntity); if(outLogs){ logger.info(String.format("[%s]响应内容: %s", url, result)); System.out.println(String.format("[%s]响应内容: %s", url, result)); } return result; } catch (Exception e) { e.printStackTrace(); logger.error("推送异常/" + e.toString() + ": " + content); return null; } } }