构造模拟远程发送http请求
构造模拟远程发送http请求
HttpClientUtils.java
package com.crs.ticket.utils; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import net.sf.json.JSONObject; import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.HttpMethodParams; public class HttpClientUtils { //单例 HttpClient 对象 private static HttpClient httpClient = null; //空构造 private HttpClientUtils() { } //返回 HttpClient 单个实例 public static HttpClient getInstance() { if (httpClient == null) { httpClient = new HttpClient(); //RFC_2109是支持较普遍的一个,还有其他cookie协议 httpClient.getParams().setCookiePolicy(CookiePolicy.RFC_2109); } return httpClient; } //关闭 HttpClient 对象 public static void CloseConnection(HttpMethod httpMethod){ httpMethod.releaseConnection(); } //使用GET方法,如果服务器需要通过HTTPS连接,那只需要将下面URL中的http换成https public static GetMethod getMethod(String url) { GetMethod getMethod = new GetMethod(url); //设置成了默认的恢复策略,在发生异常时候将自动重试3次,在这里你也可以设置成自定义的恢复策略 getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); return getMethod; } //使用POST方法 public static PostMethod postMethod(String url) { PostMethod postMethod = new PostMethod(url); //设置成了默认的恢复策略,在发生异常时候将自动重试3次,在这里你也可以设置成自定义的恢复策略 postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); return postMethod; } //使用POST方式设置参数 public static void setRequestBody(PostMethod postMethod, Map<String, String> kv){ //填入各个表单域的值 NameValuePair[] data; int size = kv.size(); data = new NameValuePair[size]; int i = 0; for (String key : kv.keySet()) { data[i] = new NameValuePair(key, kv.get(key)); i ++; } //将表单的值放入postMethod中 postMethod.addParameters(data); // postMethod.setRequestBody(data); } //执行请求并返回状态 public static int executeMethod(HttpMethod httpMethod, HttpClient client) { try { //状态,一般200为OK状态,其他情况会抛出如404,500,403等错误 return client.executeMethod(httpMethod); } catch (HttpException e) { System.out.println("发生致命的异常,可能是协议不对或者返回的内容有问题!"); } catch (IOException e) { System.out.println("发生网络异常!"); } return 0; } //第一种方式返回 byte[] public static byte[] getResponseBody(HttpMethod httpMethod) { try { return httpMethod.getResponseBody(); } catch (IOException e) { e.printStackTrace(); } return null; } //第二种方式返回 String public static String getResponseBodyAsString(HttpMethod httpMethod) { try { return httpMethod.getResponseBodyAsString(); } catch (IOException e) { e.printStackTrace(); } return null; } //第三种方式返回 InputStream public static InputStream getResponseBodyAsStream(HttpMethod httpMethod) { try { return httpMethod.getResponseBodyAsStream(); } catch (IOException e) { e.printStackTrace(); } return null; } public static void setRequestBody(PostMethod postMethod, NameValuePair[] data) { postMethod.setRequestBody(data); } public static StandardResult sendHttpMethod(String url,Map<String,String> params,String method){ String returnValue = ""; StandardResult result = new StandardResult(); HttpClient client = HttpClientUtils.getInstance(); if("get".equals(method)){ StringBuffer p = null; if(params!=null&¶ms.size()>0){ p = new StringBuffer(); for (String key : params.keySet()) { p.append(key+"="+params.get(key)+"&") ; } } if(p!=null&&p.length()>0){ url = url + p.substring(0,p.length()-1); } GetMethod method_get = getMethod(url); int status; try { //指定传送字符集为UTF-8格式 client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8"); status = client.executeMethod(method_get); if(status == Contants.HTTP_STATUS_OK){ returnValue = method_get.getResponseBodyAsString(); } } catch (Exception e) { result.setCount(0); result.setData(""); result.setMessage(Contants.MSG_API_ERROR); result.setStatus(Contants.SYSTEM_API_ERROR); return result; } }else if ("post".equals(method)) { List<NameValuePair> params_ = new ArrayList<NameValuePair>(); for (String key : params.keySet()) { params_.add(new NameValuePair(key,params.get(key))); } try { returnValue = Config.doSend(params_, url); System.out.println(returnValue); } catch (Exception e) { e.printStackTrace(); result.setCount(0); result.setData(""); result.setMessage(Contants.MSG_API_ERROR); result.setStatus(Contants.SYSTEM_API_ERROR); return result; } } if(StringUtil.isNotEmpty(returnValue)){ JSONObject json = JSONObject.fromObject(returnValue); if(StringUtil.isNotEmpty(json.getString("count"))){ result.setCount(json.getInt("count")); } result.setData(json.get("data")); result.setMessage(String.valueOf(json.get("message"))); result.setStatus(Integer.valueOf(String.valueOf(json.get("status")))); }else{ result.setCount(0); result.setData(""); result.setMessage(Contants.MSG_API_ERROR); result.setStatus(Contants.SYSTEM_API_ERROR); } return result; } }
辅助文件Config.java
package com.crs.ticket.utils; import java.util.List; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** *@Title:基础配置类 *@Description: *@Author:weidaid *@Version:1.1.0 */ public class Config { private static final Log _log = LogFactory.getLog(Config.class); // 字符编码格式 public static String input_charset = "utf-8"; // 签名方式 public static String sign_type = "MD5"; public static String doSend(List<NameValuePair> params, String gateWay) throws Exception { String requestURL = Submit.getBuildRequestPara(params, gateWay, null); _log.info("请求url:" + requestURL); String result = Submit.sendPostInfo(params, gateWay, null); _log.info("返回结果:" + result); return result; } }
辅助文件Submit.java
package com.crs.ticket.utils; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.lang.StringUtils; import com.crs.ticket.utils.httpclient.HttpProtocolHandler; import com.crs.ticket.utils.httpclient.HttpRequest; import com.crs.ticket.utils.httpclient.HttpResponse; import com.crs.ticket.utils.httpclient.HttpResultType; public class Submit { /** * 生成签名结果 * * @param sPara * 要签名的数组 * @return 签名结果字符串 */ public static String buildRequestMysign(Map<String, String> sPara, String key) { String prestr = Core.createLinkString(sPara); // 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串 String mysign = ""; if (Config.sign_type.equals("MD5")) { mysign = MD5.sign(prestr, key, Config.input_charset); } return mysign; } public static String buildRequestMysign(List<NameValuePair> sPara, String key) { String prestr = Core.createLinkString(sPara); // 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串 String mysign = ""; if (Config.sign_type.equals("MD5")) { mysign = MD5.sign(prestr, key, Config.input_charset); } return mysign; } /** * 生成要请求的参数数组 * * @param sParaTemp * 请求前的参数数组 * @return 要请求的参数数组 */ public static Map<String, String> buildRequestPara( Map<String, String> sParaTemp, String key) { // 除去数组中的空值和签名参数 Map<String, String> sPara = Core.paraFilter(sParaTemp); // 生成签名结果 String mysign = buildRequestMysign(sPara, key); // 签名结果与签名方式加入请求提交参数组中 // sPara.put("sign", mysign); // sPara.put("sign_type", Config.sign_type); return sPara; } public static List<NameValuePair> buildRequestPara( List<NameValuePair> sParaTemp, String key) { // 除去数组中的空值和签名参数 List<NameValuePair> sPara = Core.paraFilter(sParaTemp); // 生成签名结果 // String mysign = buildRequestMysign(sPara, key); // // if (StringUtils.isNotEmpty(mysign)) // mysign = mysign.toUpperCase(); // 签名结果与签名方式加入请求提交参数组中 // sPara.add(new NameValuePair("sign", mysign)); // sPara.put("sign_type", Config.sign_type); return sPara; } /** * 将url参数转换成map * * @param param * aa=11&bb=22&cc=33 * @return */ public static Map<String, Object> getUrlParams(String param) { Map<String, Object> map = new HashMap<String, Object>(0); if (StringUtils.isBlank(param)) { return map; } String[] params = param.split("&"); for (int i = 0; i < params.length; i++) { String[] p = params[i].split("="); if (p.length == 2) { map.put(p[0], p[1]); } } return map; } /** * 将map转换成url * * @param map * @return */ public static String getUrlParamsByMap(Map<String, String> map) { if (map == null) { return ""; } StringBuffer sb = new StringBuffer(); for (Map.Entry<String, String> entry : map.entrySet()) { sb.append(entry.getKey() + "=" + entry.getValue()); sb.append("&"); } String s = sb.toString(); if (s.endsWith("&")) { s = StringUtils.substringBeforeLast(s, "&"); } return s; } public static String getUrlParamsByMap(List<NameValuePair> map) { if (map == null) { return ""; } StringBuffer sb = new StringBuffer(); for (NameValuePair nameValuePair : map) { sb.append(nameValuePair.getName() + "=" + nameValuePair.getValue()); sb.append("&"); } String s = sb.toString(); if (s.endsWith("&")) { s = StringUtils.substringBeforeLast(s, "&"); } return s; } /** * MAP类型数组转换成NameValuePair类型 * * @param properties * MAP类型数组 * @return NameValuePair类型数组 */ private static NameValuePair[] generatNameValuePair( Map<String, String> properties) { NameValuePair[] nameValuePair = new NameValuePair[properties.size()]; int i = 0; for (Map.Entry<String, String> entry : properties.entrySet()) { nameValuePair[i++] = new NameValuePair(entry.getKey(), entry.getValue()); } return nameValuePair; } private static NameValuePair[] generatNameValuePair( List<NameValuePair> properties) { NameValuePair[] nameValuePair = new NameValuePair[properties.size()]; int i = 0; for (NameValuePair nvp : properties) { nameValuePair[i++] = new NameValuePair(nvp.getName(), nvp.getValue()); } return nameValuePair; } /** * 构造模拟远程HTTP的POST请求,获取处理结果 * * @param sParaTemp * 请求参数数组 * @param gateway * 网关地址 * @return 处理结果 * @throws Exception */ public static String sendPostInfo(Map<String, String> sParaTemp, String gateway, String key) throws Exception { // 待请求参数数组 Map<String, String> sPara = buildRequestPara(sParaTemp, key); HttpProtocolHandler httpProtocolHandler = HttpProtocolHandler .getInstance(); HttpRequest request = new HttpRequest(HttpResultType.BYTES); // 设置编码集 request.setCharset(Config.input_charset); System.out.println(getUrlParamsByMap(sPara)); request.setParameters(generatNameValuePair(sPara)); request.setUrl(gateway + "_input_charset=" + Config.input_charset); HttpResponse response = httpProtocolHandler.execute(request); if (response == null) { return null; } String strResult = response.getStringResult(); return strResult; } /** * 构造模拟远程HTTP的POST请求,获取处理结果 * * @param sParaTemp * 请求参数数组 * @param gateway * 网关地址 * @return 处理结果 * @throws Exception */ public static String sendPostInfo(List<NameValuePair> sParaTemp, String gateway, String key) throws Exception { // 待请求参数数组 List<NameValuePair> sPara = buildRequestPara(sParaTemp, key); HttpProtocolHandler httpProtocolHandler = HttpProtocolHandler.getInstance(); HttpRequest request = new HttpRequest(HttpResultType.BYTES); // 设置编码集 request.setCharset(Config.input_charset); //System.out.println("提交参数:" + getUrlParamsByMap(sPara)); request.setParameters(generatNameValuePair(sPara)); // System.out.println("提交URL:" + gateway + "_input_charset=" + Config.input_charset); //System.out.println("提交URL:" + gateway); request.setUrl(gateway); HttpResponse response = httpProtocolHandler.execute(request); if (response == null) { return null; } String strResult = response.getStringResult(); return strResult; } public static String sendPost(String gateway) throws Exception { HttpProtocolHandler httpProtocolHandler = HttpProtocolHandler.getInstance(); HttpRequest request = new HttpRequest(HttpResultType.BYTES); request.setCharset(Config.input_charset); //System.out.println("提交URL:" + gateway); request.setUrl(gateway); HttpResponse response = httpProtocolHandler.execute(request); if (response == null) { return null; } String strResult = response.getStringResult(); return strResult; } public static String getBuildRequestPara(List<NameValuePair> sParaTemp, String gateway, String key) throws Exception { List<NameValuePair> sPara = buildRequestPara(sParaTemp, key); return gateway + "?" + getUrlParamsByMap(sPara); } }
三个http工具类,详解下一篇
划船不用桨、杨帆不等风、一生全靠浪