HttpClient发送后台请求

由于API的不断更新,所以创建HttpClient对象和设置超时代理方式也会有细微区别

// 3.X版本
HttpClient httpClient=new DefaultHttpClient();
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,2000);//连接超时时间,毫秒

//4.3版本
CloseableHttpClient httpClient = HttpClients.createDefault();

//或者使用HttpClientBuilder对象
// 创建HttpClientBuilder 
HttpClientBuilder httpClientBuilder=HttpClientBuilder.create();
// HttpClient  
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();  

//请求地址
HttpPost post = new HttpPost(url);
//设置代理和超时
RequestConfig config=RequestConfig.custom().setConnectionRequestTimeout(30000).setProxy(httpProxyHost).build();
post.setConfig(config); 

详细变更请参考API文档,这里直接将实例

/**
 * web 请求/响应 API类
 */
public class WebUtil {


    /**
     * post 请求
     * 
     * @param url
     *            请求路径
     * @param params
     *            请求参数
     * @return 请求返回
     */
    public String post(String url, List<BasicNameValuePair> params) {
        PayLog.addLog(ELogAction.Post, EPayLogType.PostRequest, new Object[] { url, params });

        if (CheckValue.valideteNullOrEmpty(url) || params == null || params.isEmpty()) {
            return "";
        }

        String result = "";
        ProxyUtil proxyUtil=HttpRequestHelper.getProxyUtil();

        // 创建HttpClientBuilder 
        HttpClientBuilder httpClientBuilder=HttpClientBuilder.create();
        // HttpClient  
        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();  
        //请求地址
        HttpPost post = new HttpPost(url);
        RequestConfig config=null;
        //如果需要设置代理
        if (proxyUtil.getIsEnable()) {
            HttpHost httpProxyHost=new HttpHost(proxyUtil.getHost(),proxyUtil.getPort(),"http");
            config=RequestConfig.custom().setConnectionRequestTimeout(30000)
                    .setProxy(httpProxyHost).build();           
        }
        else
        {
            //超时时间设置为30s
            config=RequestConfig.custom().setConnectionRequestTimeout(30000).build();
        }
        //设置请求超时时间和有可能设置代理
        post.setConfig(config); 
        try {
            post.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
            CloseableHttpResponse response = closeableHttpClient.execute(post);

            result = parseResponse(response.getEntity().getContent());
            PayLog.addLog(ELogAction.Post, EPayLogType.PostResponse, result);

            // 释放资源  
            closeableHttpClient.close();  
        } catch (Exception ex) {

            PayLog.addErrorLog(ELogAction.Post, EPayLogType.PostResponse, ex.getMessage());
            result = "未知错误,请联系客服!";
        }
        return result;
    }

    /**
     * 解析Response信息
     * 
     * @param respStream
     *            response stream
     * @return
     */
    protected String parseResponse(InputStream respStream) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(respStream));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                respStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    /**
     * 将Response信息转为Json格式
     * 
     * @param response
     *            eg:param1=v1&param2=v2&param3=v3 ...
     * @return
     */
    public String responseToJson(String response) {
        if (CheckValue.valideteNullOrEmpty(response)) {
            return "";
        }

        Map<String, String> map = new HashMap<String, String>();

        String[] responseParams = response.split("&");
        String key = "";
        String value = "";
        for (String string : responseParams) {
            String[] keyValues = string.split("=");
            if (keyValues != null && keyValues.length > 0) {
                key = keyValues[0];
            }

            if (keyValues != null && keyValues.length > 1) {
                value = keyValues[1];
            } else {
                value = "";
            }
            map.put(key, value);
        }
        Gson gson = new Gson();
        return gson.toJson(map);
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值