网络请求工具类--HttpClientUtil

来源:互联网 发布:a阿里云矢量图标 编辑:程序博客网 时间:2024/06/05 01:19
package com.jeeplus.mobile.utils;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;


import javax.net.ssl.SSLContext;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
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.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;


import com.jeeplus.mobile.security.base64.ASEConstant;
import com.jeeplus.mobile.security.base64.BackAES;
import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;


import scala.util.parsing.json.JSONObject;


/**
 * * 功能描述:网络请求工具类
 * 
 * Version: 1.0
 * 
 * date: 2015-12-17
 * 
 * @author:Jimmy
 * 
 */
public class HttpClientUtil
{
    private static Logger logger = Logger.getLogger(HttpClientUtil.class);


    /**
     * xml参数的post请求
     * 
     * @param url
     * @param xml
     * @return
     */
    public static String post(String url, String xml)
    {
        String response = "";
        try
        {
            HttpPost post = new HttpPost(url);
            StringEntity entity = new StringEntity(xml, "utf-8");
            entity.setContentEncoding("utf-8");
            entity.setContentType("text/xml");
            post.setEntity(entity);
            response = EntityUtils.toString(new DefaultHttpClient().execute(post).getEntity(), "utf-8");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return response;
    }


    /**
     * 发送请求(不带文件的传参)
     * 
     * @param uri
     * @param jsonObject
     * @return
     * @throws Exception
     */
    public static String post(String uri, JSONObject jsonObject) throws Exception
    {
        logger.info("发送请求:" + uri + ",jsonStr:" + jsonObject.toString());
        String url = uri;
        DefaultHttpClient httpclient = new DefaultHttpClient();
        String data = new String(BackAES.encrypt(jsonObject.toString(), ASEConstant.ASE_KEY, 0));
        Map<String, String> params = new HashMap<String, String>();
        params.put("data", data);


        HttpPost httpost = new HttpPost(url);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        Set<String> keySet = params.keySet();
        for (String key : keySet)
        {
            nvps.add(new BasicNameValuePair(key, params.get(key)));
        }
        httpost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
        HttpResponse response = httpclient.execute(httpost);
        HttpEntity entity = response.getEntity();
        String body = EntityUtils.toString(entity);
        httpclient.getConnectionManager().shutdown();
        logger.info("接口返回的数据为:" + body);
        return body;
    }
    




    /**
* 发送HTTP_GET请求

* @see 该方法会自动关闭连接,释放资源
* @param requestURL
*            请求地址(含参数)
* @param decodeCharset
*            解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
* @return 远程主机响应正文
*/
public static String sendGetRequest(String reqURL, String decodeCharset) {
long responseLength = 0; // 响应长度
String responseContent = null; // 响应内容
HttpClient httpClient = new DefaultHttpClient(); // 创建默认的httpClient实例
HttpGet httpGet = new HttpGet(reqURL); // 创建org.apache.http.client.methods.HttpGet
try {
HttpResponse response = httpClient.execute(httpGet); // 执行GET请求
HttpEntity entity = response.getEntity(); // 获取响应实体
if (null != entity) {
responseLength = entity.getContentLength();
responseContent = EntityUtils.toString(entity, decodeCharset == null ? "UTF-8" : decodeCharset);
EntityUtils.consume(entity); // Consume response content
}
logger.info("请求地址: " + httpGet.getURI());
logger.info("响应状态: " + response.getStatusLine());
logger.info("响应长度: " + responseLength);
logger.info("响应内容: " + responseContent);
} catch (ClientProtocolException e) {
logger.debug("该异常通常是协议错误导致,比如构造HttpGet对象时传入的协议不对(将'http'写成'htp')或者服务器端返回的内容不符合HTTP协议要求等,堆栈信息如下", e);
} catch (ParseException e) {
logger.debug(e.getMessage(), e);
} catch (IOException e) {
logger.debug("该异常通常是网络原因引起的,如HTTP服务器未启动等,堆栈信息如下", e);
} finally {
httpClient.getConnectionManager().shutdown(); // 关闭连接,释放资源
}
return responseContent;
}


public static String executeBySslPost(String url, String body) throws Exception {
        String result = "";
        //商户id
        //指定读取证书格式为PKCS12
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        //读取本机存放的PKCS12证书文件
        FileInputStream instream = new FileInputStream(new File(PaymentConst.SSLCERT_PATH));
        try {
            //指定PKCS12的密码(商户ID)
        keyStore.load(instream, PaymentConst.WECHAT_MCHID.toCharArray());
        } finally {
            instream.close();
        }
     /*   SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, PaymentConst.WECHAT_MCHID.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();*/
        SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, PaymentConst.WECHAT_MCHID.toCharArray()).build();
        //指定TLS版本
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1"}, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        //设置httpclient的SSLSocketFactory
        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        try {
            HttpPost httppost = new HttpPost(url);
            StringEntity reqEntity = new StringEntity(body, "UTF-8");
            httppost.setEntity(reqEntity);


            System.out.println("Executing request: " + httppost.getRequestLine());
            CloseableHttpResponse response = null;
            try {
                response = httpclient.execute(httppost);
                result = EntityUtils.toString(response.getEntity(),"UTF-8");
            } catch (Exception e) {
                e.printStackTrace();
               // log.error("请求失败", e);
                throw new RuntimeException(e);
            } finally {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
           // log.error("请求失败", e);
            throw new RuntimeException(e);
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


}