httpClient中的cookie失效时间处理

问题描述:在使用配置参数进行登录成功, 第一次发送请求的结果返回之后, 10多分钟后再次发送请求会报未登录错误,正常来说不应该这样,因为目标url的session失效时间比这久

这样设置之后,短时间内可以 , 但当再次发送请求时还是会出现连接断开问题
 因为httpclientCloseableHttpClient,所以无法用从cookieStore获取

设置httpClient策略 : 设置保持时间 , 避免出现连接断开
CloseableHttpClient hc = HttpClients.custom()
        .setUserAgent("Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)")
        .setDefaultHeaders(defaultHeaders).setRedirectStrategy(new LaxRedirectStrategy())
        .setConnectionManager(cm)
        .setDefaultRequestConfig(requestConfig)
        .setDefaultCookieStore(cookieStore)
        //keep-alive时间过期之后,会主动杀掉连接,并且不会通知客户端,导致conn reset,因此在此设置keep-alive时间避免这种情况
        .setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
            @Override
            public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                return 30 * 1000;
            }
        })
        .build();



另附上传图片post方法:  http://blog.csdn.net/zknxx/article/details/72760315
public static Map<String, Object> doHttpPost(String url, InputStream is, String fileId, CloseableHttpClient httpClient)
        throws ClientProtocolException, IOException, Exception {
    logger.info("=== begin request, do http post ===>" + url);

    Map<String, Object> map = new HashMap<String, Object>();
    CloseableHttpResponse response = null;
    HttpEntity entity = null;
    HttpPost  httpPost = null;

    try {
        httpPost = new HttpPost(url);
        HttpEntity reqFile = MultipartEntityBuilder.create()
                .setContentType(ContentType.MULTIPART_FORM_DATA)
                .setBoundary("----WebKitFormBoundaryriApLsyI1shPEGEH")
                .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                .addBinaryBody("files", is, ContentType.MULTIPART_FORM_DATA, fileId)
                .build();
        httpPost.setEntity(reqFile);
        response = httpClient.execute(httpPost);
        logger.info("上传文件的respons:" + response.toString());
        entity = response.getEntity();
        String content = EntityUtils.toString(entity, "UTF-8");
        logger.info("上传文件返回Json信息 : " + content);
        map.put("content" , content);
    } catch (Exception e) {
        logger.info("=== do http post exception ===",e);
        httpPost.abort();
        throw e;
    } finally {
        if (entity != null) {
            try {
                EntityUtils.consume(entity);
            } catch (Exception e) {
            }
        }
    }
    return map;
}





评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值