public static String httpGetSend(String url) {String responseMsg = "";HttpClient httpClient = new HttpClient();GetMethod getMethod = new GetMethod(url);// GET请求try {// http超时5秒httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);// 设置 get 请求超时为 5 秒getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());httpClient.executeMethod(getMethod);// 发送请求// 读取内容byte[] responseBody = getMethod.getResponseBody();// 处理返回的内容responseMsg = new String(responseBody, "utf-8");} catch (Exception e) {Logger.getLogger(HttpUtils.class).error(e.getMessage());e.printStackTrace();} finally {getMethod.releaseConnection();// 关闭连接 }return responseMsg;}
/*** 发送HTTP请求* * @param url* @param propsMap* 发送的参数*/public static String httpSend(String url, Map<String, Object> propsMap) {String responseMsg = "";HttpClient httpClient = new HttpClient();PostMethod postMethod = new PostMethod(url);// POST请求// postMethod.// 参数设置Set<String> keySet = propsMap.keySet();NameValuePair[] postData = new NameValuePair[keySet.size()];int index = 0;for (String key : keySet) {postData[index++] = new NameValuePair(key, propsMap.get(key).toString());}postMethod.addParameters(postData);try {httpClient.executeMethod(postMethod);// 发送请求 // Log.info(postMethod.getStatusCode());// 读取内容byte[] responseBody = postMethod.getResponseBody();// 处理返回的内容responseMsg = new String(responseBody);} catch (HttpException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {postMethod.releaseConnection();// 关闭连接 }return responseMsg;}
/*** 发送HTTP请求* * @param url* @param propsMap 发送的参数* @throws IOException*/private String httpSend(String url, Map<String, Object> propsMap) {String responseMsg = "";HttpClient httpClient = new HttpClient();PostMethod postMethod = new PostMethod(url);// POST请求// 参数设置Set<String> keySet = propsMap.keySet();NameValuePair[] postData = new NameValuePair[keySet.size()];int index = 0;for (String key : keySet) {postData[index++] = new NameValuePair(key, propsMap.get(key) == null ? null : propsMap.get(key).toString());}postMethod.addParameters(postData);try {httpClient.executeMethod(postMethod);// 发送请求// 读取内容byte[] responseBody = postMethod.getResponseBody();// 处理返回的内容// responseMsg = URLDecoder.decode(new String(responseBody),// "UTF-8");responseMsg = new String(responseBody, "UTF-8");} catch (HttpException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {postMethod.releaseConnection();// 关闭连接 }return responseMsg;}
package com.huayuan.wap.common.utils;import java.io.IOException; import java.util.Map; import java.util.Set;import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.HttpMethodParams;import com.huayuan.wap.common.model.HttpResponse;public class HttpUtils {/*** 发送HTTP请求** @param url* @param propsMap 发送的参数*/public static HttpResponse httpPost(String url, Map<String, Object> propsMap) {HttpResponse response = new HttpResponse();String responseMsg = "";HttpClient httpClient = new HttpClient();PostMethod postMethod = new PostMethod(url);// POST请求if (propsMap != null) {// 参数设置Set<String> keySet = propsMap.keySet();NameValuePair[] postData = new NameValuePair[keySet.size()];int index = 0;for (String key : keySet) {postData[index++] = new NameValuePair(key, propsMap.get(key).toString());}postMethod.addParameters(postData);}postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");try {int statusCode = httpClient.executeMethod(postMethod);// 发送请求 response.setStatusCode(statusCode);if (statusCode == HttpStatus.SC_OK) {// 读取内容byte[] responseBody = postMethod.getResponseBody();// 处理返回的内容responseMsg = new String(responseBody, "utf-8");}} catch (HttpException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {postMethod.releaseConnection();// 关闭连接 }response.setContent(responseMsg);return response;}/*** 发送HTTP请求** @param url*/public static HttpResponse httpGet(String url) {HttpResponse response = new HttpResponse();String responseMsg = "";HttpClient httpClient = new HttpClient();GetMethod getMethod = new GetMethod(url);try {int statusCode = httpClient.executeMethod(getMethod);// 发送请求 response.setStatusCode(statusCode);if (statusCode == HttpStatus.SC_OK) {// 读取内容byte[] responseBody = getMethod.getResponseBody();// 处理返回的内容responseMsg = new String(responseBody, "utf-8");}} catch (HttpException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {getMethod.releaseConnection();// 关闭连接 }response.setContent(responseMsg);return response;} }
package com.j1.mai.util;import java.io.IOException; import java.util.Map; import java.util.Set;import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.log4j.Logger;public class HttpUtils {/*** 发送HTTP请求** @param url* @param propsMap 发送的参数*/public static HttpResponse httpPost(String url, Map<String, Object> propsMap) {HttpResponse response = new HttpResponse();String responseMsg = "";HttpClient httpClient = new HttpClient();PostMethod postMethod = new PostMethod(url);// POST请求if (propsMap != null) {// 参数设置Set<String> keySet = propsMap.keySet();NameValuePair[] postData = new NameValuePair[keySet.size()];int index = 0;for (String key : keySet) {postData[index++] = new NameValuePair(key, propsMap.get(key).toString());}postMethod.addParameters(postData);}postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");try {int statusCode = httpClient.executeMethod(postMethod);// 发送请求 response.setStatusCode(statusCode);if (statusCode == HttpStatus.SC_OK) {// 读取内容byte[] responseBody = postMethod.getResponseBody();// 处理返回的内容responseMsg = new String(responseBody, "utf-8");}} catch (HttpException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {postMethod.releaseConnection();// 关闭连接 }response.setContent(responseMsg);return response;}/*** 发送HTTP请求** @param url*/public static HttpResponse httpGet(String url) {HttpResponse response = new HttpResponse();String responseMsg = "";HttpClient httpClient = new HttpClient();GetMethod getMethod = new GetMethod(url);try {int statusCode = httpClient.executeMethod(getMethod);// 发送请求 response.setStatusCode(statusCode);if (statusCode == HttpStatus.SC_OK) {// 读取内容byte[] responseBody = getMethod.getResponseBody();// 处理返回的内容responseMsg = new String(responseBody, "utf-8");}} catch (HttpException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {getMethod.releaseConnection();// 关闭连接 }response.setContent(responseMsg);return response;}/*** 发送HTTP--GET请求* * @param url* @param propsMap* 发送的参数*/public static String httpGetSend(String url) {String responseMsg = "";HttpClient httpClient = new HttpClient();GetMethod getMethod = new GetMethod(url);// GET请求try {// http超时5秒httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);// 设置 get 请求超时为 5 秒getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());httpClient.executeMethod(getMethod);// 发送请求// 读取内容byte[] responseBody = getMethod.getResponseBody();// 处理返回的内容responseMsg = new String(responseBody, "utf-8");} catch (Exception e) {Logger.getLogger(HttpUtils.class).error(e.getMessage());e.printStackTrace();} finally {getMethod.releaseConnection();// 关闭连接 }return responseMsg;}/*** 发送HTTP请求* * @param url* @param propsMap* 发送的参数*/public static String httpSend(String url, Map<String, Object> propsMap) {String responseMsg = "";HttpClient httpClient = new HttpClient();PostMethod postMethod = new PostMethod(url);// POST请求// postMethod.// 参数设置Set<String> keySet = propsMap.keySet();NameValuePair[] postData = new NameValuePair[keySet.size()];int index = 0;for (String key : keySet) {postData[index++] = new NameValuePair(key, propsMap.get(key).toString());}postMethod.addParameters(postData);try {httpClient.executeMethod(postMethod);// 发送请求 // Log.info(postMethod.getStatusCode());// 读取内容byte[] responseBody = postMethod.getResponseBody();// 处理返回的内容responseMsg = new String(responseBody);} catch (HttpException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {postMethod.releaseConnection();// 关闭连接 }return responseMsg;}/*** 发送Post HTTP请求* * @param url* @param propsMap* 发送的参数* @throws IOException * @throws HttpException */public static PostMethod httpSendPost(String url, Map<String, Object> propsMap,String authrition) throws Exception {HttpClient httpClient = new HttpClient();PostMethod postMethod = new PostMethod(url);// POST请求postMethod.addRequestHeader("Authorization",authrition);postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8"); // 参数设置Set<String> keySet = propsMap.keySet();NameValuePair[] postData = new NameValuePair[keySet.size()];int index = 0;for (String key : keySet) {postData[index++] = new NameValuePair(key, propsMap.get(key).toString());}postMethod.addParameters(postData);httpClient.executeMethod(postMethod);// 发送请求return postMethod;}/*** 发送Post HTTP请求* * @param url* @param propsMap* 发送的参数* @throws IOException * @throws HttpException */public static PostMethod httpSendPost(String url, Map<String, Object> propsMap) throws Exception {String responseMsg = "";HttpClient httpClient = new HttpClient();PostMethod postMethod = new PostMethod(url);// POST请求postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8"); // 参数设置Set<String> keySet = propsMap.keySet();NameValuePair[] postData = new NameValuePair[keySet.size()];int index = 0;for (String key : keySet) {postData[index++] = new NameValuePair(key, propsMap.get(key).toString());}postMethod.addParameters(postData);httpClient.executeMethod(postMethod);// 发送请求return postMethod;}/*** 发送Get HTTP请求* * @param url* @param propsMap* 发送的参数* @throws IOException * @throws HttpException */public static GetMethod httpSendGet(String url, Map<String, Object> propsMap) throws Exception {String responseMsg = "";HttpClient httpClient = new HttpClient();GetMethod getMethod = new GetMethod(url);// GET请求getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8"); // 参数设置Set<String> keySet = propsMap.keySet();NameValuePair[] postData = new NameValuePair[keySet.size()];int index = 0;for (String key : keySet) {getMethod.getParams().setParameter(key, propsMap.get(key).toString());}httpClient.executeMethod(getMethod);// 发送请求return getMethod;}}
package com.founder.ec.member.util;import java.io.IOException; import java.util.Map; import java.util.Set;import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod;public class HttpUtils {/*** 发送HTTP请求* * @param url* @param propsMap* 发送的参数*/public static String httpSend(String url, Map<String, Object> propsMap) {String responseMsg = "";HttpClient httpClient = new HttpClient();PostMethod postMethod = new PostMethod(url);// POST请求// 参数设置Set<String> keySet = propsMap.keySet();NameValuePair[] postData = new NameValuePair[keySet.size()];int index = 0;for (String key : keySet) {postData[index++] = new NameValuePair(key, propsMap.get(key).toString());}postMethod.addParameters(postData);try {httpClient.executeMethod(postMethod);// 发送请求// 读取内容byte[] responseBody = postMethod.getResponseBody();// 处理返回的内容responseMsg = new String(responseBody);} catch (HttpException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {postMethod.releaseConnection();// 关闭连接 }return responseMsg;} }
package com.founder.ec.dec.util;import java.io.IOException;import lombok.extern.log4j.Log4j;import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.log4j.Logger;/*** http请求实体类* * @author Yang Yang 2015年11月13日 下午5:20:43* @since 1.0.0*/ public class HttpUtils {/*** post发送http请求* * @param url* @param data* @return*/public static String sendHttpPost(String url, String data) {Logger log = Logger.getRootLogger();String responseMsg = "";HttpClient httpClient = new HttpClient();httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");PostMethod postMethod = new PostMethod(url);// POST请求// 参数设置postMethod.addParameter("param", data);try {httpClient.executeMethod(postMethod);// 发送请求// 读取内容byte[] responseBody = postMethod.getResponseBody();// 处理返回的内容responseMsg = new String(responseBody, "UTF-8");} catch (HttpException e) {log.error(e.getMessage());} catch (IOException e) {log.error(e.getMessage());} finally {postMethod.releaseConnection();// 关闭连接 }return responseMsg;} }
package com.founder.ec.web.util.payments.yeepay;import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory;import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.*; /**** <p>Title: </p>* <p>Description: http utils </p>* <p>Copyright: Copyright (c) 2006</p>* <p>Company: </p>* @author LiLu* @version 1.0*/ public class HttpUtils {private static final String URL_PARAM_CONNECT_FLAG = "&";private static final int SIZE = 1024 * 1024;private static Log log = LogFactory.getLog(HttpUtils.class);private HttpUtils() {}/*** GET METHOD* @param strUrl String* @param map Map* @throws java.io.IOException* @return List*/public static List URLGet(String strUrl, Map map) throws IOException {String strtTotalURL = "";List result = new ArrayList();if(strtTotalURL.indexOf("?") == -1) {strtTotalURL = strUrl + "?" + getUrl(map);} else {strtTotalURL = strUrl + "&" + getUrl(map);} // System.out.println("strtTotalURL:" + strtTotalURL);URL url = new URL(strtTotalURL);HttpURLConnection con = (HttpURLConnection) url.openConnection();con.setUseCaches(false);con.setFollowRedirects(true);BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()),SIZE);while (true) {String line = in.readLine();if (line == null) {break;}else {result.add(line);}}in.close();return (result);}/*** POST METHOD* @param strUrl String* @param content Map* @throws java.io.IOException* @return List*/public static List URLPost(String strUrl, Map map) throws IOException {String content = "";content = getUrl(map);String totalURL = null;if(strUrl.indexOf("?") == -1) {totalURL = strUrl + "?" + content;} else {totalURL = strUrl + "&" + content;}URL url = new URL(strUrl);HttpURLConnection con = (HttpURLConnection) url.openConnection();con.setDoInput(true);con.setDoOutput(true);con.setAllowUserInteraction(false);con.setUseCaches(false);con.setRequestMethod("POST");con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=GBK");BufferedWriter bout = new BufferedWriter(new OutputStreamWriter(con.getOutputStream()));bout.write(content);bout.flush();bout.close();BufferedReader bin = new BufferedReader(new InputStreamReader(con.getInputStream()),SIZE);List result = new ArrayList(); while (true) {String line = bin.readLine();if (line == null) {break;}else {result.add(line);}}return (result);}/*** ���URL* @param map Map* @return String*/private static String getUrl(Map map) {if (null == map || map.keySet().size() == 0) {return ("");}StringBuffer url = new StringBuffer();Set keys = map.keySet();for (Iterator i = keys.iterator(); i.hasNext(); ) {String key = String.valueOf(i.next());if (map.containsKey(key)) {Object val = map.get(key);String str = val!=null?val.toString():"";try {str = URLEncoder.encode(str, "GBK");} catch (UnsupportedEncodingException e) {e.printStackTrace();}url.append(key).append("=").append(str).append(URL_PARAM_CONNECT_FLAG);}}String strURL = "";strURL = url.toString();if (URL_PARAM_CONNECT_FLAG.equals("" + strURL.charAt(strURL.length() - 1))) {strURL = strURL.substring(0, strURL.length() - 1);}return (strURL);}/*** http 发送方法* @param strUrl 请求URL* @param content 请求内容* @return 响应内容* @throws org.apache.commons.httpclient.HttpException* @throws java.io.IOException*/public static String post(String strUrl,String content)throws IOException {URL url = new URL(strUrl);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setDoOutput(true);connection.setDoInput(true);connection.setRequestMethod("POST");connection.setUseCaches(false);connection.setInstanceFollowRedirects(true);connection.setRequestProperty("Content-Type","text/plain;charset=UTF-8");connection.connect();// POST请求DataOutputStream out = new DataOutputStream(connection.getOutputStream());out.write(content.getBytes("utf-8"));out.flush();out.close();// 读取响应BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));String lines;StringBuffer sb = new StringBuffer("");while ((lines = reader.readLine()) != null) {lines = new String(lines.getBytes(), "utf-8");sb.append(lines);}reader.close();// 断开连接 connection.disconnect();return sb.toString();}}
package com.founder.ec.utils;import net.sf.json.JSONObject;import javax.net.ssl.*; import java.io.*; import java.net.URL; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Map;public class HttpsUtils {private static class TrustAnyTrustManager implements X509TrustManager {public void checkClientTrusted(X509Certificate[] chain, String authType)throws CertificateException {}public void checkServerTrusted(X509Certificate[] chain, String authType)throws CertificateException {}public X509Certificate[] getAcceptedIssuers() {return new X509Certificate[] {};}}private static class TrustAnyHostnameVerifier implements HostnameVerifier {public boolean verify(String hostname, SSLSession session) {return true;}}/*** post方式请求服务器(https协议)** @param url* 请求地址* @param content* 参数* @param charset* 编码* @return* @throws NoSuchAlgorithmException* @throws KeyManagementException* @throws IOException*/@SuppressWarnings("static-access")public static String post(String url, Map<String, Object> content, String charset)throws NoSuchAlgorithmException, KeyManagementException,IOException {String responseContent = null;SSLContext sc = SSLContext.getInstance("SSL");sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },new java.security.SecureRandom());URL console = new URL(url);HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();conn.setSSLSocketFactory(sc.getSocketFactory());conn.setHostnameVerifier(new TrustAnyHostnameVerifier());conn.setDoOutput(true);conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");conn.connect();JSONObject obj = new JSONObject();obj = obj.fromObject(content);byte[] b = obj.toString().getBytes();DataOutputStream out = new DataOutputStream(conn.getOutputStream());out.write(b, 0, b.length);// 刷新、关闭 out.flush();out.close();InputStream in = conn.getInputStream();BufferedReader rd = new BufferedReader(new InputStreamReader(in,"UTF-8"));String tempLine = rd.readLine();StringBuffer tempStr = new StringBuffer();String crlf=System.getProperty("line.separator");while (tempLine != null){tempStr.append(tempLine);tempStr.append(crlf);tempLine = rd.readLine();}responseContent = tempStr.toString();rd.close();in.close();if (conn != null){conn.disconnect();}return responseContent;}}
package com.founder.ec.web.util;import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Map;import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager;import net.sf.json.JSONObject;public class HttpsUtils {private static class TrustAnyTrustManager implements X509TrustManager {public void checkClientTrusted(X509Certificate[] chain, String authType)throws CertificateException {}public void checkServerTrusted(X509Certificate[] chain, String authType)throws CertificateException {}public X509Certificate[] getAcceptedIssuers() {return new X509Certificate[] {};}}private static class TrustAnyHostnameVerifier implements HostnameVerifier {public boolean verify(String hostname, SSLSession session) {return true;}}/*** post方式请求服务器(https协议)** @param url* 请求地址* @param content* 参数* @param charset* 编码* @return* @throws NoSuchAlgorithmException* @throws KeyManagementException* @throws IOException*/@SuppressWarnings("static-access")public static String post(String url, Map<String, Object> content, String charset)throws NoSuchAlgorithmException, KeyManagementException,IOException {String responseContent = null;SSLContext sc = SSLContext.getInstance("SSL");sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },new java.security.SecureRandom());URL console = new URL(url);HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();conn.setSSLSocketFactory(sc.getSocketFactory());conn.setHostnameVerifier(new TrustAnyHostnameVerifier());conn.setDoOutput(true);conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");conn.connect();JSONObject obj = new JSONObject();obj = obj.fromObject(content);byte[] b = obj.toString().getBytes();DataOutputStream out = new DataOutputStream(conn.getOutputStream());out.write(b, 0, b.length);// 刷新、关闭 out.flush();out.close();InputStream in = conn.getInputStream();BufferedReader rd = new BufferedReader(new InputStreamReader(in,"UTF-8"));String tempLine = rd.readLine();StringBuffer tempStr = new StringBuffer();String crlf=System.getProperty("line.separator");while (tempLine != null){tempStr.append(tempLine);tempStr.append(crlf);tempLine = rd.readLine();}responseContent = tempStr.toString();rd.close();in.close();if (conn != null){conn.disconnect();}return responseContent;}}
/*** 华润通联合登陆*//****联合登录获取华润通的用户信息** appid,* access_token,* openid,* sign,* timestamp,* 通过code获取token 与openId*/@RequestMapping(value = "/getHrtCode")public String hrt(HttpServletRequest request, HttpServletResponse response,String code,String state) {JSONObject object = new JSONObject();JSONObject data = new JSONObject();String memberKey="";/**** 读取配置文件拿到华润通数据*/String hrtUrl=PropertyConfigurer.getString("hrtUrl");if(StringUtil.isEmpty(hrtUrl)){hrtUrl = "https://oauth2.huaruntong.cn/oauth2/access_token";}String hrtAppId=PropertyConfigurer.getString("hrtAppId");if(StringUtil.isEmpty(hrtAppId)){hrtAppId = "1655100000004";}String hrtSignKey=PropertyConfigurer.getString("hrtSignKey");if(StringUtil.isEmpty(hrtSignKey)){hrtSignKey = "tmKBcdNCTeyvDLTQFkYtbDdHBUwHZEmSZlNFbUhxHqQOjgev";}// //获取当前时间SimpleDateFormat sd=new SimpleDateFormat("yyyyMMddHHmmss");String timestamp= sd.format(new Date());String sign = "appid="+hrtAppId+"&code="+code+"&grant_type=authorization_code×tamp="+timestamp+"&app_secret="+hrtSignKey;sign = MD5.getMD5(sign).toUpperCase();/***发送请求*/try {Map<String,Object> map = new HashMap<String , Object>();map.put("appid", hrtAppId);map.put("gant_type", grantType);map.put("code", code);map.put("timestamp", timestamp);map.put("sign",sign);String back = HttpsUtils.post(hrtUrl, map, "UTF-8");if(!back.isEmpty() || back!=null){object= JSONObject.fromObject(back);data= object.getJSONObject("data");if( data.size()!=0 ){String openId= data.getString("openid");// 异常处理if (null == openId || "".equals(openId) ) {request.setAttribute("errors", "授权失败,请重新授权!");return "/jsp/common/404.jsp";}ServiceMessage<com.j1.member.model.Member> result= memberSsoService.hrtFastLogin(openId);if(result.getStatus() == MsgStatus.NORMAL){com.j1.member.model.Member member= result.getResult();memberKey = result.getResult().getMemberKey();if(member!=null){request.getSession().setAttribute("memberId", member.getMemberId());request.getSession().setAttribute("loginName", member.getLoginName());request.getSession().setAttribute("realName", member.getRealName());request.getSession().setAttribute("member", member);request.getSession().setAttribute("mobile",member.getMobile());request.getSession().setAttribute("memberKey", result.getResult().getMemberKey());return "redirect:https://www.j1.com?memberKey"+memberKey;}}}}} catch (Exception e) {e.printStackTrace();logger.error("华瑞通系统内部报错");}return "redirect:https://www.j1.com?memberKey"+memberKey;}
package com.founder.ec.web.util.payments.payeco.http;import com.founder.ec.web.util.payments.payeco.http.ssl.SslConnection;import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.Iterator; import java.util.SortedMap;/*** 描述: http通讯基础类* */ public class HttpClient {private int status;public int getStatus() {return status;}public void setStatus(int status) {this.status = status;}public static String REQUEST_METHOD_GET = "GET";public static String REQUEST_METHOD_POST = "POST";public String send(String postURL, String requestBody,String sendCharset, String readCharset) {return send(postURL,requestBody,sendCharset,readCharset,300,300);}public String send(String postURL, String requestBody,String sendCharset, String readCharset,String RequestMethod) {return send(postURL,requestBody,sendCharset,readCharset,300,300,RequestMethod);}/*** @param postURL 访问地址* @param requestBody paramName1=paramValue1¶mName2=paramValue2* @param sendCharset 发送字符编码* @param readCharset 返回字符编码* @param connectTimeout 连接主机的超时时间 单位:秒* @param readTimeout 从主机读取数据的超时时间 单位:秒* @return 通讯返回*/public String send(String url, String requestBody,String sendCharset, String readCharset,int connectTimeout,int readTimeout) {try {return connection(url,requestBody,sendCharset,readCharset,connectTimeout,readTimeout,REQUEST_METHOD_POST);} catch (Exception ex) {ex.printStackTrace();System.out.print("发送请求[" + url + "]失败," + ex.getMessage());return null;} }/*** @param postURL 访问地址* @param requestBody paramName1=paramValue1¶mName2=paramValue2* @param sendCharset 发送字符编码* @param readCharset 返回字符编码* @param connectTimeout 连接主机的超时时间 单位:秒* @param readTimeout 从主机读取数据的超时时间 单位:秒* @param RequestMethod GET或POST* @return 通讯返回*/public String send(String url, String requestBody,String sendCharset, String readCharset,int connectTimeout,int readTimeout,String RequestMethod) {try {return connection(url,requestBody,sendCharset,readCharset,connectTimeout,readTimeout,RequestMethod);} catch (Exception ex) {ex.printStackTrace();System.out.print("发送请求[" + url + "]失败," + ex.getMessage());return null;} }public String connection(String postURL, String requestBody,String sendCharset, String readCharset,int connectTimeout,int readTimeout,String RequestMethod)throws Exception {if(REQUEST_METHOD_POST.equals(RequestMethod)){return postConnection(postURL,requestBody,sendCharset,readCharset,connectTimeout,readTimeout,null);}else if(REQUEST_METHOD_GET.equals(RequestMethod)){return getConnection(postURL,requestBody,sendCharset,readCharset,connectTimeout,readTimeout,null);}else{return "";}}@SuppressWarnings("rawtypes")public String getConnection(String url, String requestBody,String sendCharset, String readCharset,int connectTimeout,int readTimeout,SortedMap reqHead)throws Exception {// Post请求的url,与get不同的是不需要带参数HttpURLConnection httpConn = null;try {if (!url.contains("https:")) {URL postUrl = new URL(url);// 打开连接httpConn = (HttpURLConnection) postUrl.openConnection();} else {SslConnection urlConnect = new SslConnection();httpConn = (HttpURLConnection) urlConnect.openConnection(url);}httpConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded; charset=" + sendCharset);if(reqHead!=null&&reqHead.size()>0){Iterator iterator =reqHead.keySet().iterator();while (iterator.hasNext()) {String key = (String) iterator.next();String val = (String)reqHead.get(key);httpConn.setRequestProperty(key,val);}}// 设定传送的内容类型是可序列化的java对象 // (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException) httpUrlConnection.setRequestProperty("Content-type", "application/x-java-serialized-object"); // 连接主机的超时时间(单位:毫秒)httpConn.setConnectTimeout(1000 * connectTimeout); // 从主机读取数据的超时时间(单位:毫秒) httpConn.setReadTimeout(1000 * readTimeout);// 连接,从postUrl.openConnection()至此的配置必须要在 connect之前完成,// 要注意的是connection.getOutputStream会隐含的进行 connect。 httpConn.connect();int status = httpConn.getResponseCode();setStatus(status);if (status != HttpURLConnection.HTTP_OK) {System.out.print("发送请求失败,状态码:[" + status + "] 返回信息:"+ httpConn.getResponseMessage());return null;}BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), readCharset));StringBuffer responseSb = new StringBuffer();String line = null;while ((line = reader.readLine()) != null) {responseSb.append(line.trim());}reader.close();return responseSb.toString().trim();} finally {httpConn.disconnect();}}@SuppressWarnings("rawtypes")public String postConnection(String postURL, String requestBody,String sendCharset, String readCharset,int connectTimeout,int readTimeout,SortedMap reqHead)throws Exception {// Post请求的url,与get不同的是不需要带参数HttpURLConnection httpConn = null;try {if (!postURL.contains("https:")) {URL postUrl = new URL(postURL);// 打开连接httpConn = (HttpURLConnection) postUrl.openConnection();} else {SslConnection urlConnect = new SslConnection();httpConn = (HttpURLConnection) urlConnect.openConnection(postURL);}// 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在 // http正文内,因此需要设为true, 默认情况下是false; httpConn.setDoOutput(true);// 设置是否从httpUrlConnection读入,默认情况下是true; httpConn.setDoInput(true);// 设定请求的方法为"POST",默认是GET httpConn.setRequestMethod("POST");// Post 请求不能使用缓存 httpConn.setUseCaches(false);//进行跳转httpConn.setInstanceFollowRedirects(true);httpConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded; charset=" + sendCharset);if(reqHead!=null&&reqHead.size()>0){Iterator iterator =reqHead.keySet().iterator();while (iterator.hasNext()) {String key = (String) iterator.next();String val = (String)reqHead.get(key);httpConn.setRequestProperty(key,val);}}// 设定传送的内容类型是可序列化的java对象 // (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException) httpUrlConnection.setRequestProperty("Content-type", "application/x-java-serialized-object"); // 连接主机的超时时间(单位:毫秒)httpConn.setConnectTimeout(1000 * connectTimeout); // 从主机读取数据的超时时间(单位:毫秒) httpConn.setReadTimeout(1000 * readTimeout);// 连接,从postUrl.openConnection()至此的配置必须要在 connect之前完成,// 要注意的是connection.getOutputStream会隐含的进行 connect。 httpConn.connect();DataOutputStream out = new DataOutputStream(httpConn.getOutputStream());out.write(requestBody.getBytes(sendCharset));out.flush();out.close();int status = httpConn.getResponseCode();setStatus(status);if (status != HttpURLConnection.HTTP_OK) {System.out.print("发送请求失败,状态码:[" + status + "] 返回信息:"+ httpConn.getResponseMessage());return null;}BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), readCharset));StringBuffer responseSb = new StringBuffer();String line = null;while ((line = reader.readLine()) != null) {responseSb.append(line.trim());}reader.close();return responseSb.toString().trim();} finally {httpConn.disconnect();}}public static void main(String[] args) {}}
package com.founder.ec.web.util.payments.tenpay; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.UnrecoverableKeyException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.util.HashMap; import java.util.Map;import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; public class HttpClientUtil {public static final String SunX509 = "SunX509";public static final String JKS = "JKS";public static final String PKCS12 = "PKCS12";public static final String TLS = "TLS";/*** get HttpURLConnection* @param strUrl url地址* @return HttpURLConnection* @throws IOException*/public static HttpURLConnection getHttpURLConnection(String strUrl)throws IOException {URL url = new URL(strUrl);HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();return httpURLConnection;}/*** get HttpsURLConnection* @param strUrl url地址* @return HttpsURLConnection* @throws IOException*/public static HttpsURLConnection getHttpsURLConnection(String strUrl)throws IOException {URL url = new URL(strUrl);HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();return httpsURLConnection;}/*** 获取不带查询串的url* @param strUrl* @return String*/public static String getURL(String strUrl) {if(null != strUrl) {int indexOf = strUrl.indexOf("?");if(-1 != indexOf) {return strUrl.substring(0, indexOf);} return strUrl;}return strUrl;}/*** 获取查询串* @param strUrl* @return String*/public static String getQueryString(String strUrl) {if(null != strUrl) {int indexOf = strUrl.indexOf("?");if(-1 != indexOf) {return strUrl.substring(indexOf+1, strUrl.length());} return "";}return strUrl;}/*** 查询字符串转换成Map<br/>* name1=key1&name2=key2&...* @param queryString* @return*/public static Map queryString2Map(String queryString) {if(null == queryString || "".equals(queryString)) {return null;}Map m = new HashMap();String[] strArray = queryString.split("&");for(int index = 0; index < strArray.length; index++) {String pair = strArray[index];HttpClientUtil.putMapByPair(pair, m);}return m;}/*** 把键值添加至Map<br/>* pair:name=value* @param pair name=value* @param m*/public static void putMapByPair(String pair, Map m) {if(null == pair || "".equals(pair)) {return;}int indexOf = pair.indexOf("=");if(-1 != indexOf) {String k = pair.substring(0, indexOf);String v = pair.substring(indexOf+1, pair.length());if(null != k && !"".equals(k)) {m.put(k, v);}} else {m.put(pair, "");}}/*** BufferedReader转换成String<br/>* 注意:流关闭需要自行处理* @param reader* @return String* @throws IOException*/public static String bufferedReader2String(BufferedReader reader) throws IOException {StringBuffer buf = new StringBuffer();String line = null;while( (line = reader.readLine()) != null) {buf.append(line);buf.append("\r\n");}return buf.toString();}/*** 处理输出<br/>* 注意:流关闭需要自行处理* @param out* @param data* @param len* @throws IOException*/public static void doOutput(OutputStream out, byte[] data, int len) throws IOException {int dataLen = data.length;int off = 0;while(off < dataLen) {if(len >= dataLen) {out.write(data, off, dataLen);} else {out.write(data, off, len);}//刷新缓冲区 out.flush();off += len;dataLen -= len;}}/*** 获取SSLContext* @param trustFile * @param trustPasswd* @param keyFile* @param keyPasswd* @return* @throws NoSuchAlgorithmException * @throws KeyStoreException * @throws IOException * @throws CertificateException * @throws UnrecoverableKeyException * @throws KeyManagementException */public static SSLContext getSSLContext(FileInputStream trustFileInputStream, String trustPasswd,FileInputStream keyFileInputStream, String keyPasswd)throws NoSuchAlgorithmException, KeyStoreException,CertificateException, IOException, UnrecoverableKeyException,KeyManagementException {// caTrustManagerFactory tmf = TrustManagerFactory.getInstance(HttpClientUtil.SunX509);KeyStore trustKeyStore = KeyStore.getInstance(HttpClientUtil.JKS);trustKeyStore.load(trustFileInputStream, HttpClientUtil.str2CharArray(trustPasswd));tmf.init(trustKeyStore);final char[] kp = HttpClientUtil.str2CharArray(keyPasswd);KeyManagerFactory kmf = KeyManagerFactory.getInstance(HttpClientUtil.SunX509);KeyStore ks = KeyStore.getInstance(HttpClientUtil.PKCS12);ks.load(keyFileInputStream, kp);kmf.init(ks, kp);SecureRandom rand = new SecureRandom();SSLContext ctx = SSLContext.getInstance(HttpClientUtil.TLS);ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), rand);return ctx;}/*** 获取CA证书信息* @param cafile CA证书文件* @return Certificate* @throws CertificateException* @throws IOException*/public static Certificate getCertificate(File cafile)throws CertificateException, IOException {CertificateFactory cf = CertificateFactory.getInstance("X.509");FileInputStream in = new FileInputStream(cafile);Certificate cert = cf.generateCertificate(in);in.close();return cert;}/*** 字符串转换成char数组* @param str* @return char[]*/public static char[] str2CharArray(String str) {if(null == str) return null;return str.toCharArray();}/*** 存储ca证书成JKS格式* @param cert* @param alias* @param password* @param out* @throws KeyStoreException* @throws NoSuchAlgorithmException* @throws CertificateException* @throws IOException*/public static void storeCACert(Certificate cert, String alias,String password, OutputStream out) throws KeyStoreException,NoSuchAlgorithmException, CertificateException, IOException {KeyStore ks = KeyStore.getInstance("JKS");ks.load(null, null);ks.setCertificateEntry(alias, cert);// store keystore ks.store(out, HttpClientUtil.str2CharArray(password));}public static InputStream String2Inputstream(String str) {return new ByteArrayInputStream(str.getBytes());} }
package com.founder.ec.common.utils;import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.UnrecoverableKeyException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.util.HashMap; import java.util.Map;import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory;import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory;public class HttpClientUtil {private static final Log logger = LogFactory.getLog(HttpClientUtil.class);public static byte[] doHttpClient(String url) {HttpClient c = new HttpClient();GetMethod getMethod = new GetMethod(url);try {getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,5000);getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());int statusCode = c.executeMethod(getMethod);if (statusCode != HttpStatus.SC_OK) {logger.error("doHttpClient Method failed: "+ getMethod.getStatusLine());}else{return getMethod.getResponseBody();}} catch (Exception e) {logger.error("doHttpClient errot : "+e.getMessage());} finally {getMethod.releaseConnection();}return null;}//财付通public static final String SunX509 = "SunX509";public static final String JKS = "JKS";public static final String PKCS12 = "PKCS12";public static final String TLS = "TLS";/*** get HttpURLConnection* @param strUrl url地址* @return HttpURLConnection* @throws IOException*/public static HttpURLConnection getHttpURLConnection(String strUrl)throws IOException {URL url = new URL(strUrl);HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();return httpURLConnection;}/*** get HttpsURLConnection* @param strUrl url地址* @return HttpsURLConnection* @throws IOException*/public static HttpsURLConnection getHttpsURLConnection(String strUrl)throws IOException {URL url = new URL(strUrl);HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();return httpsURLConnection;}/*** 获取不带查询串的url* @param strUrl* @return String*/public static String getURL(String strUrl) {if(null != strUrl) {int indexOf = strUrl.indexOf("?");if(-1 != indexOf) {return strUrl.substring(0, indexOf);} return strUrl;}return strUrl;}/*** 获取查询串* @param strUrl* @return String*/public static String getQueryString(String strUrl) {if(null != strUrl) {int indexOf = strUrl.indexOf("?");if(-1 != indexOf) {return strUrl.substring(indexOf+1, strUrl.length());} return "";}return strUrl;}/*** 查询字符串转换成Map<br/>* name1=key1&name2=key2&...* @param queryString* @return*/public static Map queryString2Map(String queryString) {if(null == queryString || "".equals(queryString)) {return null;}Map m = new HashMap();String[] strArray = queryString.split("&");for(int index = 0; index < strArray.length; index++) {String pair = strArray[index];HttpClientUtil.putMapByPair(pair, m);}return m;}/*** 把键值添加至Map<br/>* pair:name=value* @param pair name=value* @param m*/public static void putMapByPair(String pair, Map m) {if(null == pair || "".equals(pair)) {return;}int indexOf = pair.indexOf("=");if(-1 != indexOf) {String k = pair.substring(0, indexOf);String v = pair.substring(indexOf+1, pair.length());if(null != k && !"".equals(k)) {m.put(k, v);}} else {m.put(pair, "");}}/*** BufferedReader转换成String<br/>* 注意:流关闭需要自行处理* @param reader* @return String* @throws IOException*/public static String bufferedReader2String(BufferedReader reader) throws IOException {StringBuffer buf = new StringBuffer();String line = null;while( (line = reader.readLine()) != null) {buf.append(line);buf.append("\r\n");}return buf.toString();}/*** 处理输出<br/>* 注意:流关闭需要自行处理* @param out* @param data* @param len* @throws IOException*/public static void doOutput(OutputStream out, byte[] data, int len) throws IOException {int dataLen = data.length;int off = 0;while(off < dataLen) {if(len >= dataLen) {out.write(data, off, dataLen);} else {out.write(data, off, len);}//刷新缓冲区 out.flush();off += len;dataLen -= len;}}/*** 获取SSLContext* @param trustFile * @param trustPasswd* @param keyFile* @param keyPasswd* @return* @throws NoSuchAlgorithmException * @throws KeyStoreException * @throws IOException * @throws CertificateException * @throws UnrecoverableKeyException * @throws KeyManagementException */public static SSLContext getSSLContext(FileInputStream trustFileInputStream, String trustPasswd,FileInputStream keyFileInputStream, String keyPasswd)throws NoSuchAlgorithmException, KeyStoreException,CertificateException, IOException, UnrecoverableKeyException,KeyManagementException {// caTrustManagerFactory tmf = TrustManagerFactory.getInstance(HttpClientUtil.SunX509);KeyStore trustKeyStore = KeyStore.getInstance(HttpClientUtil.JKS);trustKeyStore.load(trustFileInputStream, HttpClientUtil.str2CharArray(trustPasswd));tmf.init(trustKeyStore);final char[] kp = HttpClientUtil.str2CharArray(keyPasswd);KeyManagerFactory kmf = KeyManagerFactory.getInstance(HttpClientUtil.SunX509);KeyStore ks = KeyStore.getInstance(HttpClientUtil.PKCS12);ks.load(keyFileInputStream, kp);kmf.init(ks, kp);SecureRandom rand = new SecureRandom();SSLContext ctx = SSLContext.getInstance(HttpClientUtil.TLS);ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), rand);return ctx;}/*** 获取CA证书信息* @param cafile CA证书文件* @return Certificate* @throws CertificateException* @throws IOException*/public static Certificate getCertificate(File cafile)throws CertificateException, IOException {CertificateFactory cf = CertificateFactory.getInstance("X.509");FileInputStream in = new FileInputStream(cafile);Certificate cert = cf.generateCertificate(in);in.close();return cert;}/*** 字符串转换成char数组* @param str* @return char[]*/public static char[] str2CharArray(String str) {if(null == str) return null;return str.toCharArray();}/*** 存储ca证书成JKS格式* @param cert* @param alias* @param password* @param out* @throws KeyStoreException* @throws NoSuchAlgorithmException* @throws CertificateException* @throws IOException*/public static void storeCACert(Certificate cert, String alias,String password, OutputStream out) throws KeyStoreException,NoSuchAlgorithmException, CertificateException, IOException {KeyStore ks = KeyStore.getInstance("JKS");ks.load(null, null);ks.setCertificateEntry(alias, cert);// store keystore ks.store(out, HttpClientUtil.str2CharArray(password));}public static InputStream String2Inputstream(String str) {return new ByteArrayInputStream(str.getBytes());} }
package com.j1.website.util;import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Map; import java.util.Set;import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod;public class HttpClientUtil {/*** 发送HTTP请求* * @param url 接口地址* @param propsMap* 发送的参数*/public static String httpSend(String url, Map<String, Object> propsMap) {String responseMsg = "";HttpClient httpClient = new HttpClient();PostMethod postMethod = new PostMethod(url);// POST请求// 参数设置Set<String> keySet = propsMap.keySet();NameValuePair[] postData = new NameValuePair[keySet.size()];int index = 0;for (String key : keySet) {postData[index++] = new NameValuePair(key, propsMap.get(key).toString());}postMethod.addParameters(postData);try {httpClient.executeMethod(postMethod);// 发送请求// 读取内容BufferedReader reader = new BufferedReader(new InputStreamReader(postMethod.getResponseBodyAsStream()));// byte[] responseBody = postMethod.getResponseBody();// 处理返回的内容// responseMsg = new String(responseBody);StringBuffer stringBuffer = new StringBuffer();String str;while ((str = reader.readLine()) != null) {stringBuffer.append(str);}responseMsg = stringBuffer.toString();} catch (HttpException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {postMethod.releaseConnection();// 关闭连接 }return responseMsg;} }
package com.founder.ec.web.util.payments.weixin;import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.UnrecoverableKeyException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.util.HashMap; import java.util.Map;import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory;import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.SSLContexts; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients;/*** Http客户端工具类<br/>* 这是内部调用类,请不要在外部调用。* @author miklchen**/ public class HttpClientUtil {public static final String SunX509 = "SunX509";public static final String JKS = "JKS";public static final String PKCS12 = "PKCS12";public static final String TLS = "TLS";/*** get HttpURLConnection* @param strUrl url地址* @return HttpURLConnection* @throws IOException*/public static HttpURLConnection getHttpURLConnection(String strUrl)throws IOException {URL url = new URL(strUrl);HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();return httpURLConnection;}/*** get HttpsURLConnection* @param strUrl url地址* @return HttpsURLConnection* @throws IOException*/public static HttpsURLConnection getHttpsURLConnection(String strUrl)throws IOException {URL url = new URL(strUrl);HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();return httpsURLConnection;}/*** 获取不带查询串的url* @param strUrl* @return String*/public static String getURL(String strUrl) {if(null != strUrl) {int indexOf = strUrl.indexOf("?");if(-1 != indexOf) {return strUrl.substring(0, indexOf);} return strUrl;}return strUrl;}/*** 获取查询串* @param strUrl* @return String*/public static String getQueryString(String strUrl) {if(null != strUrl) {int indexOf = strUrl.indexOf("?");if(-1 != indexOf) {return strUrl.substring(indexOf+1, strUrl.length());} return "";}return strUrl;}/*** 查询字符串转换成Map<br/>* name1=key1&name2=key2&...* @param queryString* @return*/public static Map queryString2Map(String queryString) {if(null == queryString || "".equals(queryString)) {return null;}Map m = new HashMap();String[] strArray = queryString.split("&");for(int index = 0; index < strArray.length; index++) {String pair = strArray[index];HttpClientUtil.putMapByPair(pair, m);}return m;}/*** 把键值添加至Map<br/>* pair:name=value* @param pair name=value* @param m*/public static void putMapByPair(String pair, Map m) {if(null == pair || "".equals(pair)) {return;}int indexOf = pair.indexOf("=");if(-1 != indexOf) {String k = pair.substring(0, indexOf);String v = pair.substring(indexOf+1, pair.length());if(null != k && !"".equals(k)) {m.put(k, v);}} else {m.put(pair, "");}}/*** BufferedReader转换成String<br/>* 注意:流关闭需要自行处理* @param reader* @return String* @throws IOException*/public static String bufferedReader2String(BufferedReader reader) throws IOException {StringBuffer buf = new StringBuffer();String line = null;while( (line = reader.readLine()) != null) {buf.append(line);buf.append("\r\n");}return buf.toString();}/*** 处理输出<br/>* 注意:流关闭需要自行处理* @param out* @param data* @param len* @throws IOException*/public static void doOutput(OutputStream out, byte[] data, int len)throws IOException {int dataLen = data.length;int off = 0;while (off < data.length) {if (len >= dataLen) {out.write(data, off, dataLen);off += dataLen;} else {out.write(data, off, len);off += len;dataLen -= len;}// 刷新缓冲区 out.flush();}}/*** 获取SSLContext* @param trustFile * @param trustPasswd* @param keyFile* @param keyPasswd* @return* @throws NoSuchAlgorithmException * @throws KeyStoreException * @throws IOException * @throws CertificateException * @throws UnrecoverableKeyException * @throws KeyManagementException */public static SSLContext getSSLContext(FileInputStream trustFileInputStream, String trustPasswd,FileInputStream keyFileInputStream, String keyPasswd)throws NoSuchAlgorithmException, KeyStoreException,CertificateException, IOException, UnrecoverableKeyException,KeyManagementException {// caTrustManagerFactory tmf = TrustManagerFactory.getInstance(HttpClientUtil.SunX509);KeyStore trustKeyStore = KeyStore.getInstance(HttpClientUtil.JKS);trustKeyStore.load(trustFileInputStream, HttpClientUtil.str2CharArray(trustPasswd));tmf.init(trustKeyStore);final char[] kp = HttpClientUtil.str2CharArray(keyPasswd);KeyManagerFactory kmf = KeyManagerFactory.getInstance(HttpClientUtil.SunX509);KeyStore ks = KeyStore.getInstance(HttpClientUtil.PKCS12);ks.load(keyFileInputStream, kp);kmf.init(ks, kp);SecureRandom rand = new SecureRandom();SSLContext ctx = SSLContext.getInstance(HttpClientUtil.TLS);ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), rand);return ctx;}/*** 获取CA证书信息* @param cafile CA证书文件* @return Certificate* @throws CertificateException* @throws IOException*/public static Certificate getCertificate(File cafile)throws CertificateException, IOException {CertificateFactory cf = CertificateFactory.getInstance("X.509");FileInputStream in = new FileInputStream(cafile);Certificate cert = cf.generateCertificate(in);in.close();return cert;}/*** 字符串转换成char数组* @param str* @return char[]*/public static char[] str2CharArray(String str) {if(null == str) return null;return str.toCharArray();}/*** 存储ca证书成JKS格式* @param cert* @param alias* @param password* @param out* @throws KeyStoreException* @throws NoSuchAlgorithmException* @throws CertificateException* @throws IOException*/public static void storeCACert(Certificate cert, String alias,String password, OutputStream out) throws KeyStoreException,NoSuchAlgorithmException, CertificateException, IOException {KeyStore ks = KeyStore.getInstance("JKS");ks.load(null, null);ks.setCertificateEntry(alias, cert);// store keystore ks.store(out, HttpClientUtil.str2CharArray(password));}public static InputStream String2Inputstream(String str) {return new ByteArrayInputStream(str.getBytes());}/*** InputStream转换成Byte* 注意:流关闭需要自行处理* @param in* @return byte* @throws Exception*/public static byte[] InputStreamTOByte(InputStream in) throws IOException{ int BUFFER_SIZE = 4096; ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] data = new byte[BUFFER_SIZE]; int count = -1; while((count = in.read(data,0,BUFFER_SIZE)) != -1) outStream.write(data, 0, count); data = null; byte[] outByte = outStream.toByteArray();outStream.close();return outByte; } /*** InputStream转换成String* 注意:流关闭需要自行处理* @param in* @param encoding 编码* @return String* @throws Exception*/public static String InputStreamTOString(InputStream in,String encoding) throws IOException{ return new String(InputStreamTOByte(in),encoding);}/*** 微信退款http请求* * @param certFilePath* @param password* @param orderRefundUrl* @param packageXml* @return* @throws Exception*/public static String refund4WxHttpClient(String certFilePath, String password, String orderRefundUrl, StringBuffer packageXml) throws Exception{StringBuffer retXmlContent = new StringBuffer();//获取商户证书KeyStore keyStore = KeyStore.getInstance("PKCS12");FileInputStream instream = new FileInputStream(new File(certFilePath));try {keyStore.load(instream, password.toCharArray());} finally {instream.close();}// Trust own CA and all self-signed certsSSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, password.toCharArray()).build();// Allow TLSv1 protocol onlySSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,new String[] { "TLSv1" },null,SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();try {HttpPost httppost = new HttpPost(orderRefundUrl);StringEntity myEntity = new StringEntity(packageXml.toString(), "UTF-8"); httppost.setEntity(myEntity);CloseableHttpResponse response = httpclient.execute(httppost);try {HttpEntity entity = response.getEntity();if (entity != null) {BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent(), "utf-8"));String text;while ((text = bufferedReader.readLine()) != null) {retXmlContent.append(text);}} // EntityUtils.consume(entity);} finally {response.close();}} finally {httpclient.close();}return retXmlContent.toString();} }
package com.founder.ec.web.util.payments.weixin.client;import com.founder.ec.web.util.payments.weixin.HttpClientUtil;import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import java.io.*; import java.net.HttpURLConnection; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate;/*** 财付通http或者https网络通信客户端<br/>* ========================================================================<br/>* api说明:<br/>* setReqContent($reqContent),设置请求内容,无论post和get,都用get方式提供<br/>* getResContent(), 获取应答内容<br/>* setMethod(method),设置请求方法,post或者get<br/>* getErrInfo(),获取错误信息<br/>* setCertInfo(certFile, certPasswd),设置证书,双向https时需要使用<br/>* setCaInfo(caFile), 设置CA,格式未pem,不设置则不检查<br/>* setTimeOut(timeOut), 设置超时时间,单位秒<br/>* getResponseCode(), 取返回的http状态码<br/>* call(),真正调用接口<br/>* getCharset()/setCharset(),字符集编码<br/>* * ========================================================================<br/>**/ public class TenpayHttpClient {private static final String USER_AGENT_VALUE = "Mozilla/4.0 (compatible; MSIE 6.0; Windows XP)";private static final String JKS_CA_FILENAME = "tenpay_cacert.jks";private static final String JKS_CA_ALIAS = "tenpay";private static final String JKS_CA_PASSWORD = "1222075301";/** ca证书文件 */private File caFile;/** 证书文件 */private File certFile;/** 证书密码 */private String certPasswd;/** 请求内容,无论post和get,都用get方式提供 */private String reqContent;/** 应答内容 */private String resContent;/** 请求方法 */private String method;/** 错误信息 */private String errInfo;/** 超时时间,以秒为单位 */private int timeOut;/** http应答编码 */private int responseCode;/** 字符编码 */private String charset;private InputStream inputStream;public TenpayHttpClient() {this.caFile = null;this.certFile = null;this.certPasswd = "";this.reqContent = "";this.resContent = "";this.method = "POST";this.errInfo = "";this.timeOut = 30;//30秒this.responseCode = 0;this.charset = "GBK";this.inputStream = null;}/*** 设置证书信息* @param certFile 证书文件* @param certPasswd 证书密码*/public void setCertInfo(File certFile, String certPasswd) {this.certFile = certFile;this.certPasswd = certPasswd;}/*** 设置ca* @param caFile*/public void setCaInfo(File caFile) {this.caFile = caFile;}/*** 设置请求内容* @param reqContent 表求内容*/public void setReqContent(String reqContent) {this.reqContent = reqContent;}/*** 获取结果内容* @return String* @throws IOException */public String getResContent() {try {this.doResponse();} catch (IOException e) {this.errInfo = e.getMessage();//return ""; }return this.resContent;}/*** 设置请求方法post或者get* @param method 请求方法post/get*/public void setMethod(String method) {this.method = method;}/*** 获取错误信息* @return String*/public String getErrInfo() {return this.errInfo;}/*** 设置超时时间,以秒为单位* @param timeOut 超时时间,以秒为单位*/public void setTimeOut(int timeOut) {this.timeOut = timeOut;}/*** 获取http状态码* @return int*/public int getResponseCode() {return this.responseCode;}/*** 执行http调用。true:成功 false:失败* @return boolean*/public boolean call() {boolean isRet = false;//httpif(null == this.caFile && null == this.certFile) {try {this.callHttp();isRet = true;} catch (IOException e) {this.errInfo = e.getMessage();}return isRet;}//httpstry {this.callHttps();isRet = true;} catch (UnrecoverableKeyException e) {this.errInfo = e.getMessage();} catch (KeyManagementException e) {this.errInfo = e.getMessage();} catch (CertificateException e) {this.errInfo = e.getMessage();} catch (KeyStoreException e) {this.errInfo = e.getMessage();} catch (NoSuchAlgorithmException e) {this.errInfo = e.getMessage();} catch (IOException e) {this.errInfo = e.getMessage();}return isRet;}protected void callHttp() throws IOException {if("POST".equals(this.method.toUpperCase())) {String url = HttpClientUtil.getURL(this.reqContent);String queryString = HttpClientUtil.getQueryString(this.reqContent);byte[] postData = queryString.getBytes(this.charset);this.httpPostMethod(url, postData);return ;}this.httpGetMethod(this.reqContent);} protected void callHttps() throws IOException, CertificateException,KeyStoreException, NoSuchAlgorithmException,UnrecoverableKeyException, KeyManagementException {// ca目录String caPath = this.caFile.getParent();File jksCAFile = new File(caPath + "/"+ TenpayHttpClient.JKS_CA_FILENAME);if (!jksCAFile.isFile()) {X509Certificate cert = (X509Certificate) HttpClientUtil.getCertificate(this.caFile);FileOutputStream out = new FileOutputStream(jksCAFile);// store jks file HttpClientUtil.storeCACert(cert, TenpayHttpClient.JKS_CA_ALIAS,TenpayHttpClient.JKS_CA_PASSWORD, out);out.close();}FileInputStream trustStream = new FileInputStream(jksCAFile);FileInputStream keyStream = new FileInputStream(this.certFile);SSLContext sslContext = HttpClientUtil.getSSLContext(trustStream,TenpayHttpClient.JKS_CA_PASSWORD, keyStream, this.certPasswd);//关闭流 keyStream.close();trustStream.close();if("POST".equals(this.method.toUpperCase())) {String url = HttpClientUtil.getURL(this.reqContent);String queryString = HttpClientUtil.getQueryString(this.reqContent);byte[] postData = queryString.getBytes(this.charset);this.httpsPostMethod(url, postData, sslContext);return ;}this.httpsGetMethod(this.reqContent, sslContext);}public boolean callHttpPost(String url, String postdata) {boolean flag = false;byte[] postData;try {postData = postdata.getBytes(this.charset);this.httpPostMethod(url, postData);flag = true;} catch (IOException e1) {e1.printStackTrace();}return flag;}/*** 以http post方式通信* @param url* @param postData* @throws IOException*/protected void httpPostMethod(String url, byte[] postData)throws IOException {HttpURLConnection conn = HttpClientUtil.getHttpURLConnection(url);this.doPost(conn, postData);}/*** 以http get方式通信* * @param url* @throws IOException*/protected void httpGetMethod(String url) throws IOException {HttpURLConnection httpConnection =HttpClientUtil.getHttpURLConnection(url);this.setHttpRequest(httpConnection);httpConnection.setRequestMethod("GET");this.responseCode = httpConnection.getResponseCode();this.inputStream = httpConnection.getInputStream();}/*** 以https get方式通信* @param url* @param sslContext* @throws IOException*/protected void httpsGetMethod(String url, SSLContext sslContext)throws IOException {SSLSocketFactory sf = sslContext.getSocketFactory();HttpsURLConnection conn = HttpClientUtil.getHttpsURLConnection(url);conn.setSSLSocketFactory(sf);this.doGet(conn);}protected void httpsPostMethod(String url, byte[] postData,SSLContext sslContext) throws IOException {SSLSocketFactory sf = sslContext.getSocketFactory();HttpsURLConnection conn = HttpClientUtil.getHttpsURLConnection(url);conn.setSSLSocketFactory(sf);this.doPost(conn, postData);}/*** 设置http请求默认属性* @param httpConnection*/protected void setHttpRequest(HttpURLConnection httpConnection) {//设置连接超时时间httpConnection.setConnectTimeout(this.timeOut * 1000);//User-AgenthttpConnection.setRequestProperty("User-Agent", TenpayHttpClient.USER_AGENT_VALUE);//不使用缓存httpConnection.setUseCaches(false);//允许输入输出httpConnection.setDoInput(true);httpConnection.setDoOutput(true);}/*** 处理应答* @throws IOException*/protected void doResponse() throws IOException {if(null == this.inputStream) {return;}//获取应答内容this.resContent=HttpClientUtil.InputStreamTOString(this.inputStream,this.charset); //关闭输入流this.inputStream.close();}/*** post方式处理* @param conn* @param postData* @throws IOException*/protected void doPost(HttpURLConnection conn, byte[] postData)throws IOException {// 以post方式通信conn.setRequestMethod("POST");// 设置请求默认属性this.setHttpRequest(conn);// Content-Typeconn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream());final int len = 1024; // 1KB HttpClientUtil.doOutput(out, postData, len);// 关闭流 out.close();// 获取响应返回状态码this.responseCode = conn.getResponseCode();// 获取应答输入流this.inputStream = conn.getInputStream();}/*** get方式处理* @param conn* @throws IOException*/protected void doGet(HttpURLConnection conn) throws IOException {//以GET方式通信conn.setRequestMethod("GET");//设置请求默认属性this.setHttpRequest(conn);//获取响应返回状态码this.responseCode = conn.getResponseCode();//获取应答输入流this.inputStream = conn.getInputStream();}}