package www.gateway.utils.http; import java.io.File; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.http.entity.mime.content.ByteArrayBody; import org.apache.http.entity.mime.content.FileBody; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * HTTP工具类,封装HttpClient4.x来对外提供简化的HTTP请求 * @author apollo.liuzhenghai * @date 2015-10-21 */ public class HttpHelper { private static Logger logger = LoggerFactory.getLogger(HttpHelper.class); private static Integer socketTimeout = 15000; private static Integer connectTimeout = 15000; private static Integer connectionRequestTimeout = 15000; //此变量请勿他用 private static int TIMES_INTEVAL = 0; /** * 使用Get方式 根据URL地址,获取ResponseConten * * @param url ip port * 完整的URL地址 * @return ResponseContent 如果发生异常则返回null,否则返回ResponseContent对象 */ public static synchronized ResponseContent getUrl(String url,String ip ,String port) { HttpClientWrapper hw = new HttpClientWrapper(connectionRequestTimeout, connectTimeout, socketTimeout); ResponseContent response = null; try { response = hw.getResponse(url,ip,port); TIMES_INTEVAL = 0; } catch (Exception e) { logger.error("连接异常:"+e.getMessage()); TIMES_INTEVAL++; if(TIMES_INTEVAL < 3){ getUrl(url,ip,port); }else{ TIMES_INTEVAL = 0; } } return response; } public static void main(String[] args) { getUrl(null,null,null); getUrl(null,null,null); } /** * 使用Get方式 根据URL地址,获取ResponseContent对象 * * @param url * 完整的URL地址 * @return ResponseContent 如果发生异常则返回null,否则返回ResponseContent对象 */ public static ResponseContent getUrlRespContent(String url) { HttpClientWrapper hw = new HttpClientWrapper(connectionRequestTimeout, connectTimeout, socketTimeout); ResponseContent response = null; try { response = hw.getResponse(url); } catch (Exception e) { logger.error("连接异常:"+e.getMessage()); e.printStackTrace(); } return response; } /** * 使用Get方式 根据URL地址,获取ResponseContent对象 * * @param url * 完整的URL地址 * @param urlEncoding * 编码,可以为null * @return ResponseContent 如果发生异常则返回null,否则返回ResponseContent对象 */ public static ResponseContent getUrlRespContent(String url, String urlEncoding) { HttpClientWrapper hw = new HttpClientWrapper(connectionRequestTimeout, connectTimeout, socketTimeout); ResponseContent response = null; try { response = hw.getResponse(url, urlEncoding); } catch (Exception e) { logger.error("连接异常:"+e.getMessage()); e.printStackTrace(); } return response; } /** * 将参数拼装在url中,进行post请求。 * * @param url * @return */ public static ResponseContent postUrl(String url) { HttpClientWrapper hw = new HttpClientWrapper(); ResponseContent ret = null; try { setParams(url, hw); ret = hw.postNV(url); } catch (Exception e) { e.printStackTrace(); } return ret; } private static void setParams(String url, HttpClientWrapper hw) { String[] paramStr = url.split("[?]", 2); if (paramStr == null || paramStr.length != 2) { return; } String[] paramArray = paramStr[1].split("[&]"); if (paramArray == null) { return; } for (String param : paramArray) { if (param == null || "".equals(param.trim())) { continue; } String[] keyValue = param.split("[=]", 2); if (keyValue == null || keyValue.length != 2) { continue; } hw.addNV(keyValue[0], keyValue[1]); } } /** * 上传文件(包括图片) * * @param url * 请求URL * @param paramsMap * 参数和值 * @return */ public static ResponseContent postEntity(String url, Map<String, Object> paramsMap) { HttpClientWrapper hw = new HttpClientWrapper(); ResponseContent ret = null; try { setParams(url, hw); Iterator<String> iterator = paramsMap.keySet().iterator(); while (iterator.hasNext()) { String key = iterator.next(); Object value = paramsMap.get(key); if (value instanceof File) { FileBody fileBody = new FileBody((File) value); hw.getContentBodies().add(fileBody); } else if (value instanceof byte[]) { byte[] byteVlue = (byte[]) value; ByteArrayBody byteArrayBody = new ByteArrayBody(byteVlue, key); hw.getContentBodies().add(byteArrayBody); } else { if (value != null && !"".equals(value)) { hw.addNV(key, String.valueOf(value)); } else { hw.addNV(key, ""); } } } ret = hw.postEntity(url); } catch (Exception e) { e.printStackTrace(); } return ret; } /** * 使用post方式,发布对象转成的json给Rest服务。 * * @param url * @param jsonBody * @return */ public static ResponseContent postJsonEntity(String url, String jsonBody) { return postEntity(url, jsonBody, "application/json"); } /** * 使用post方式,发布对象转成的xml给Rest服务 * * @param url * URL地址 * @param xmlBody * xml文本字符串 * @return ResponseContent 如果发生异常则返回空,否则返回ResponseContent对象 */ public static ResponseContent postXmlEntity(String url, String xmlBody) { return postEntity(url, xmlBody, "application/xml"); } private static ResponseContent postEntity(String url, String body, String contentType) { HttpClientWrapper hw = new HttpClientWrapper(); ResponseContent ret = null; try { hw.addNV("body", body); ret = hw.postNV(url, contentType); } catch (Exception e) { e.printStackTrace(); } return ret; } public static void testPost() { String url = "http://www.baidu.com/"; ResponseContent responseContent = getUrlRespContent(url); try { System.out.println(responseContent.getContent()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } //test public static void testGet() { String url = "http://www.baidu.com/"; ResponseContent responseContent = getUrlRespContent(url); try { System.out.println(responseContent.getContent()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } //test public static void testUploadFile() { try { String url = "http://localhost:8280/jfly/action/admin/user/upload.do"; Map<String, Object> paramsMap = new HashMap<String, Object>(); paramsMap.put("userName", "jj"); paramsMap.put("password", "jj"); paramsMap.put("filePath", new File("C:\\Users\\yangjian1004\\Pictures\\default (1).jpeg")); ResponseContent ret = postEntity(url, paramsMap); System.out.println(ret.getContent()); } catch (Exception e) { e.printStackTrace(); } } //TODO //加个charset嘛海哥,传参数进去也行啊,还需要接受空指针异常 /** @param source 需要加密的字符串 * @param hashType 加密类型 (MD5 和 SHA) * @return * @throws UnsupportedEncodingException * @throws NoSuchAlgorithmException * @throws NullPointerException */ public static String getHash2(String source, String hashType){//,String charset StringBuilder sb = new StringBuilder(); MessageDigest md5; try { md5 = MessageDigest.getInstance(hashType); md5.update(source.getBytes("UTF-8")); for (byte b : md5.digest()) { sb.append(String.format("%02X", b)); // 10进制转16进制,X 表示以十六进制形式输出,02 表示不足两位前面补0输出 } return sb.toString(); } catch (NoSuchAlgorithmException | NullPointerException| UnsupportedEncodingException e) { e.printStackTrace(); } return null; } }