HttpClient发送后台请求

简介: 由于API的不断更新,所以创建HttpClient对象和设置超时代理方式也会有细微区别// 3.X版本HttpClient httpClient=new DefaultHttpClient();httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,2000);//连接超时

由于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);
    }

}
目录
相关文章
|
6月前
|
前端开发 API
服务端渲染-nextjs如何发起请求
服务端渲染-nextjs如何发起请求
323 0
|
Web App开发 缓存 JavaScript
如何处理页面关闭时发送HTTP请求?
在实际项目开发中,可能会遇到这样的业务问题:如何在用户离开或关闭页面时发送HTTP请求给服务端?可能有人会觉得页面都关闭了,还需要发送什么请求,完全没必要噻。但如果真有这样的业务需求落到自己的头上,那么我们应该如何来实现呢?
1869 0
如何处理页面关闭时发送HTTP请求?
|
Android开发
【OkHttp】OkHttp Get 和 Post 请求 ( 同步 Get 请求 | 异步 Get 请求 | 同步 Post 请求 | 异步 Post 请求 )(一)
【OkHttp】OkHttp Get 和 Post 请求 ( 同步 Get 请求 | 异步 Get 请求 | 同步 Post 请求 | 异步 Post 请求 )(一)
999 0
|
3月前
|
存储 JSON 监控
源码分析Zabbix客户端如何向服务端发起请求
源码分析Zabbix客户端如何向服务端发起请求
30 2
|
5月前
Axios 权限请求 一次只能发送一个请求
Axios 权限请求 一次只能发送一个请求
|
5月前
|
移动开发 网络协议 安全
C/C++ 发送与接收HTTP/S请求
HTTP(Hypertext Transfer Protocol)是一种用于传输超文本的协议。它是一种无状态的、应用层的协议,用于在计算机之间传输超文本文档,通常在 Web 浏览器和 Web 服务器之间进行数据通信。HTTP 是由互联网工程任务组(IETF)定义的,它是基于客户端-服务器模型的协议,其中客户端向服务器发送请求,服务器以相应的数据作为响应。HTTP 协议是建立在 TCP/IP 协议之上的,通常使用默认的端口号80。
115 0
C/C++ 发送与接收HTTP/S请求
|
7月前
|
JSON 小程序 API
【uniapp小程序】request发起请求
【uniapp小程序】request发起请求
108 0
|
8月前
|
存储 缓存 关系型数据库
1.6 服务器处理客户端请求
1.6 服务器处理客户端请求
48 0
axios发送请求几种方式
axios发送请求几种方式
142 0
获取网页数据 Qt 从客户端发起http响应
获取网页数据 Qt 从客户端发起http响应
177 0