Apache的HttpClient创建CloseableHttpClient的例子

来源:互联网 发布:淘宝店铺分类导航 编辑:程序博客网 时间:2024/05/16 19:55

Apache的HttpClient可以被用于从客户端发送HTTP请求到服务器端,

使用Apache的HttpClient发送GET和POST请求的步骤如下:
1. 使用帮助类HttpClients创建CloseableHttpClient对象.
2. 基于要发送的HTTP请求类型创建HttpGet或者HttpPost实例.
3. 使用addHeader方法添加请求头部,诸如User-Agent, Accept-Encoding等参数.
4. 对于POST请求,创建NameValuePair列表,并添加所有的表单参数.然后把它填充进HttpPost实体.
5. 通过执行此HttpGet或者HttpPost请求获取CloseableHttpResponse实例
6. 从此CloseableHttpResponse实例中获取状态码,错误信息,以及响应页面等等.
7. 最后关闭HttpClient资源.

    public String doPost(String url, String params) {        String result = "";        CloseableHttpClient httpclient = null;        CloseableHttpResponse response = null;        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();        HttpSession session = request.getSession();        if (session != null) {            httpclient = (CloseableHttpClient) session.getAttribute("httpclient");        }        if (httpclient == null) {            httpclient = HttpClients.createDefault();        }        try {            HttpPost httppost = new HttpPost(url);            httppost.setHeader("accept", "*/*");            httppost.setHeader("connection", "Keep-Alive");            httppost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36");            if (params != null && !"".equals(params)) {                MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();                reqEntity.setCharset(Charset.forName("utf-8"));                String[] nameAndValue = params.split("&");                for (String s : nameAndValue) {                    String[] keyAndvalue = s.split("=",2);                    //String[] keyAndvalue = s.split("=");                    StringBody value = new StringBody("", ContentType.TEXT_PLAIN);                    if(keyAndvalue.length == 2) {                        value = new StringBody(keyAndvalue[1], Charset.forName("utf-8"));                        //value = new StringBody(keyAndvalue[1],  ContentType.TEXT_PLAIN);                    }                    reqEntity.addPart(keyAndvalue[0], value);                }                HttpEntity httpEntity = reqEntity.build();                httppost.setEntity(httpEntity);            }            response = httpclient.execute(httppost);            HttpEntity resEntity = response.getEntity();            if(resEntity != null) {                result = EntityUtils.toString(resEntity, "utf-8");            }            EntityUtils.consume(resEntity);            //if (url.endsWith("center/login") || url.endsWith("#forgetPswd") || url.endsWith("#register")) {                session.setAttribute("httpclient", httpclient);            //}                //2017-08-24 解决由session过期导致请求返回会员未登录的问题                if(StringUtils.isNotBlank(result)){                    boolean isJson = Common.isJson(result);                    //有些请求不是json格式,比如医院动态                    if(isJson){                        JSONObject js = JSONObject.fromObject(result);                        //有些result没有返回code                        if(js.has("code")){                            if(ErrorCode.LS_ILLEGAL_LOGIN.equals(js.getString("code"))){                                log.info("【本次请求返回会员未登录】"+js.toString());                                //将请求信息放入缓存                                RCacheEnTity rCacheEnTity = new RCacheEnTity(url,params,new Date());                                CachePool.getInstance().putCacheItem("RC", rCacheEnTity);                                String openId = (String) request.getSession().getAttribute("openId");                                log.info("【重新登陆的openID】"+openId);                                //进行重新登陆                                String cxdl = doPost(WechatContext.getInstance().getServerUrl() + "center/wechatLogin", "username=" + openId);                                //将上次的请求信息取出                                CacheItem cacheItem = (CacheItem) CachePool.getInstance().getCacheItem("RC");                                RCacheEnTity rCacheEnTity2 = (RCacheEnTity) cacheItem.getEntity();                                log.info("【重新请求的URL】"+rCacheEnTity2.getUrl());                                //重新发送上次的请求                                String cxqq = doPost(rCacheEnTity2.getUrl(),rCacheEnTity2.getParams());                                JSONObject cx = JSONObject.fromObject(cxqq);                                //请求成功之后将缓存中的上次的请求信息去除                                if(ErrorCode.LS_SUCCESS.equals(cx.getString("code"))){                                    //如果请求成功则去除缓存                                    CachePool.getInstance().removeCacheItem("RC");                                    result=cxqq;                                }else{                                    CachePool.getInstance().removeCacheItem("RC");                                }                            }                        }                    }                }        } catch (IOException e) {            e.printStackTrace();        } finally {            try {                if (response != null) {                    response.close();                }                // httpclient.close();            } catch (IOException e1) {                e1.printStackTrace();            }        }        return result;    }
原创粉丝点击