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&timestamp="
                +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&paramName2=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&paramName2=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 {

        // ca
        TrustManagerFactory 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 {

        // ca
        TrustManagerFactory 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 {

        // ca
        TrustManagerFactory 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 certs
        SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(keyStore, password.toCharArray())
                .build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory 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;

        //http
        if(null == this.caFile && null == this.certFile) {
            try {
                this.callHttp();
                isRet = true;
            } catch (IOException e) {
                this.errInfo = e.getMessage();
            }
            return isRet;
        }

        //https
        try {
            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-Agent
        httpConnection.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-Type
        conn.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();
    }

}

发送http请求的更多相关文章

  1. Java发送Http请求并获取状态码

    通过Java发送url请求,查看该url是否有效,这时我们可以通过获取状态码来判断. try { URL u = new URL("http://10.1.2.8:8080/fqz/page ...

  2. AngularJs的$http发送POST请求,php无法接收Post的数据解决方案

      最近在使用AngularJs+Php开发中遇到php后台无法接收到来自AngularJs的数据,在网上也有许多解决方法,却都点到即止.多番摸索后记录下解决方法:tips:当前使用的AngularJ ...

  3. Ajax发送POST请求SpringMVC页面跳转失败

    问题描述:因为使用的是SpringMVC框架,所以想使用ModelAndView进行页面跳转.思路是发送POST请求,然后controller层中直接返回相应ModelAndView,但是这种方法不可 ...

  4. 使用HttpClient来异步发送POST请求并解析GZIP回应

    .NET 4.5(C#): 使用HttpClient来异步发送POST请求并解析GZIP回应 在新的C# 5.0和.NET 4.5环境下,微软为C#加入了async/await,同时还加入新的Syst ...

  5. 在发送ajax请求时加时间戳或者随机数去除js缓存

    在发送ajax请求的时候,为了保证每次的都与服务器交互,就要传递一个参数每次都不一样,这里就用了时间戳 大家在系统开发中都可能会在js中用到ajax或者dwr,因为IE的缓存,使得我们在填入相同的值的 ...

  6. HttpUrlConnection发送url请求(后台springmvc)

    1.HttpURLConnection发送url请求 public class JavaRequest { private static final String BASE_URL = "h ...

  7. kattle 发送post请求

    一.简介 kattle是一款国外开源的ETL工具,纯java编写,可以在Window.Linux.Unix上运行,数据抽取高效稳定.它允许你管理来自不同数据库的数据,通过提供一个图形化的用户环境来描述 ...

  8. 【荐】怎么用PHP发送HTTP请求(POST请求、GET请求)?

    file_get_contents版本: <?php /** * 发送post请求 * @param string $url 请求地址 * @param array $post_data pos ...

  9. 使用RestTemplate发送post请求

    最近使用RestTemplate发送post请求,遇到了很多问题,如转换httpMessage失败,中文乱码等,调了好久才找到下面较为简便的方法: RestTemplate restTemplate ...

  10. 【转载】JMeter学习(三十六)发送HTTPS请求

    Jmeter一般来说是压力测试的利器,最近想尝试jmeter和BeanShell进行接口测试.由于在云阅读接口测试的过程中需要进行登录操作,而登录请求是HTTPS协议.这就需要对jmeter进行设置. ...

随机推荐

  1. mapreduce编程(一)-二次排序

    转自:http://blog.csdn.net/heyutao007/article/details/5890103 mr自带的例子中的源码SecondarySort,我重新写了一下,基本没变. 这个 ...

  2. 两个有序单链表合并成一个有序单链表的java实现

    仅作为备注, 便于自己回顾. import java.util.Arrays; public class MergeSort { public static class LinkedNode<V ...

  3. SpannableString属性详解

    1.BackgroundColorSpan 背景色     2.ClickableSpan 文本可点击,有点击事件    3.ForegroundColorSpan 文本颜色(前景色)    4.Ma ...

  4. [转]8款实用的jQuery/CSS3最新插件应用

    今天给大家分享8款非常酷的最新jQuery/CSS3应用插件,废话少说,下面一起来看看这些插件吧. 1.HTML5重力感应积木游戏 这也是一款基于HTML5技术的重力感应游戏,一些积木从天而降,你可以 ...

  5. 7款开源ERP系统比较

    [网络转载] 现在有许多企业将ERP项目,在企 业中没有实施好,都归咎于软件产品不好.其实,这只是你们的借口.若想要将ERP软件真正与企业融合一体,首先得考虑企业的自身情况,再去选择适合的 ERP软件 ...

  6. (笔记)ubuntu中取消文件夹或文件等右下解一把锁的标志的方法

    ubuntu中取消文件夹或文件等右下解一把锁的标志的方法   方法:   sudo chmod -R 777 路径(文件夹或文件)   对文件递归做改变权限为可读可写可运行,即可.

  7. lua------------------Unity3D研究院编辑器之打开unity不可识别的文件(十三)

    Unity3D研究院编辑器之打开unity不可识别的文件(十三) 雨松MOMO [Unity3D拓展编辑器] 围观8597次 9 条评论 编辑日期:2017-03-02 字体:大 中 小   有些特殊 ...

  8. (原)关于sdl在部分机器上做视频显示,改变显示窗口大小会崩溃

    今天测试人员反应,之前做的视频绘图显示,会在她机器上,会出现崩溃现象,最后我在她机器上对代码进行跟踪,发现在某种情况,确实会崩溃. 最主要的原因是,视频显示窗口变成非活动窗口的时候,sdl内部会循环消 ...

  9. CentOS7使用firewalld打开关闭防火墙与端口[转]

    转自:http://www.cnblogs.com/moxiaoan/p/5683743.html1.firewalld的基本使用启动: systemctl start firewalld查看状态: ...

  10. vegan 包进行Adonis 分析

    Adonis 分析 是基于距离矩阵的多变量方差置换分析, 代码示例: 默认使用bray 距离来计算样本间的距离矩阵 参考资料: https://www.rdocumentation.org/packa ...