`
01jiangwei01
  • 浏览: 532923 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

可以保持session的java代码片段

    博客分类:
  • java
阅读更多
 
import java.io.File;
import java.io.IOException;
import java.util.*;

import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
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.client.protocol.HttpClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.DefaultRedirectStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.CharsetUtils;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.eclipse.jetty.util.ajax.JSON;

/**
 * 保持同一session的HttpClient工具类
 * @author zhangwenchao
 *
 */
public class HttpClientKeepSession {

    private static final Logger LOG = LogManager.getLogger(HttpClient.class);
    public  static CloseableHttpClient httpClient = null;
    public  static HttpClientContext context = null;
    public  static CookieStore cookieStore = null;
    public  static RequestConfig requestConfig = null;

    static {
        init();
    }

    private static void init() {
        context = HttpClientContext.create();
        cookieStore = new BasicCookieStore();
        // 配置超时时间(连接服务端超时1秒,请求数据返回超时2秒)
        requestConfig = RequestConfig.custom().setConnectTimeout(120000).setSocketTimeout(60000)
                .setConnectionRequestTimeout(60000).build();
        // 设置默认跳转以及存储cookie
        httpClient = HttpClientBuilder.create()
                .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())
                .setRedirectStrategy(new DefaultRedirectStrategy()).setDefaultRequestConfig(requestConfig)
                .setDefaultCookieStore(cookieStore).build();
    }

    /**
     * http get
     *
     * @param url
     * @return response
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String get(String url,Map<String,Object> params) throws Exception {
        long responseLength = 0;       //响应长度
        String responseContent = null; //响应内容
        CloseableHttpResponse response = null;

        if(params != null){
             Set<String> keySet =  params.keySet();
            Iterator<String> iterator = keySet.iterator();
            String keyString = "";
            String key  = null;
            while (iterator.hasNext()){
                key = iterator.next();
                if(keyString.length()>0){
                    keyString += "&";
                }
                keyString  += key +"="+params.get(key);
            }
            if(url.indexOf("?") > 0 ){
                url = url+"&"+keyString;
            }else {
                url = url+"?"+keyString;
            }
        }
        HttpGet httpget = new HttpGet(url);
         response = httpClient.execute(httpget, context);

        cookieStore = context.getCookieStore();
        List<Cookie> cookies = cookieStore.getCookies();
        for (Cookie cookie : cookies) {
            LOG.debug("key:" + cookie.getName() + "  value:" + cookie.getValue());
        }

        //printResponse(response);

        HttpEntity entity = null;
        if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
            entity = response.getEntity();            //获取响应实体
            if(null != entity){
                responseContent = EntityUtils.toString(entity, "UTF-8");
                EntityUtils.consume(entity); //Consume response content
            }
        }else{
            String param= null;
            if(params != null){
                param = JSON.toString(params);
            }
//            LOG.error("url="+url+"\r\n param="+param+"\r\n statecode="+response.getStatusLine().getStatusCode());
            String errorMsg = "url="+url+"\r\n param="+param+"\r\n statecode="+response.getStatusLine().getStatusCode();
            LOG.error(errorMsg);
            throw new Exception(errorMsg);
        }

        return responseContent;
    }

    /**
     * http post
     *
     * @param url
     * @param params
     *            form表单
     * @return response
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String post(String url, Map<String,String> params)
            throws Exception {
            CloseableHttpResponse response = null;
            String responseContent = null; //响应内容
            HttpPost httpPost = new HttpPost(url);
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();

            if(params != null){
                Set<String> keySet =  params.keySet();
                Iterator<String> iterator = keySet.iterator();

                String key  = null;
                while (iterator.hasNext()){
                    key = iterator.next();
                    nvps.add(new BasicNameValuePair(key, params.get(key).toString()));

                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            response = httpClient.execute(httpPost, context);

            cookieStore = context.getCookieStore();
            List<Cookie> cookies = cookieStore.getCookies();
//            for (Cookie cookie : cookies) {
//                LOG.debug("key:" + cookie.getName() + "  value:" + cookie.getValue());
//            }
          //  printResponse(response);
        HttpEntity entity = null;
        if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
            entity = response.getEntity();            //获取响应实体
            if(null != entity){
                responseContent = EntityUtils.toString(entity, "UTF-8");
                EntityUtils.consume(entity); //Consume response content
            }
        }else{
            String param= null;
            if(params != null){
                param = JSON.toString(params);
            }

            String errorMsg = "url="+url+"\r\n param="+param+"\r\n statecode="+response.getStatusLine().getStatusCode();
            LOG.error(errorMsg);
            throw new Exception(errorMsg);
        }

        return responseContent;

    }
    public static String sendPostByJson(String url, String body) throws Exception {
        CloseableHttpResponse response = null;
        String responseContent = null; //响应内容
        HttpPost httpPost = new HttpPost(url);

        if(StringUtils.isNotEmpty(body)){
            HttpEntity entity2 = new StringEntity(body, Consts.UTF_8);
            httpPost.setEntity(entity2);
        }
        response = httpClient.execute(httpPost, context);

        cookieStore = context.getCookieStore();
//        List<Cookie> cookies = cookieStore.getCookies();
//            for (Cookie cookie : cookies) {
//                LOG.debug("key:" + cookie.getName() + "  value:" + cookie.getValue());
//            }
        //  printResponse(response);
        HttpEntity entity = null;
        if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
            entity = response.getEntity();            //获取响应实体
            if(null != entity){
                responseContent = EntityUtils.toString(entity, "UTF-8");
                EntityUtils.consume(entity); //Consume response content
            }
        }else{
            String errorMsg = "url="+url+"\r\n param="+body+"\r\n statecode="+response.getStatusLine().getStatusCode();
            LOG.error(errorMsg);
            throw new Exception(errorMsg);
        }


        return responseContent;
    }

    public static void upload(String url) {
        try {
            HttpPost httppost = new HttpPost(url);
            FileBody bin = new FileBody(new File("C:\\Users\\zhangwenchao\\Desktop\\jinzhongzi.jpg"));
            HttpEntity reqEntity = MultipartEntityBuilder.create()
                    .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                    .addPart("uploadFile", bin)
                    .setCharset(CharsetUtils.get("UTF-8")).build();
            httppost.setEntity(reqEntity);
            System.out.println("executing request: "+ httppost.getRequestLine());
            CloseableHttpResponse response = httpClient.execute(httppost,context);
            try {
                cookieStore = context.getCookieStore();
                List<Cookie> cookies = cookieStore.getCookies();
                for (Cookie cookie : cookies) {
                    LOG.debug("key:" + cookie.getName() + "  value:" + cookie.getValue());
                }

                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    // 响应长度
                    System.out.println("Response content length: "
                            + resEntity.getContentLength());
                    // 打印响应内容
                    System.out.println("Response content: "
                            + EntityUtils.toString(resEntity));
                }
                // 销毁
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 手动增加cookie
     * @param name
     * @param value
     * @param domain
     * @param path
     */
    public static void addCookie(String name, String value, String domain, String path) {
        BasicClientCookie cookie = new BasicClientCookie(name, value);
        cookie.setDomain(domain);
        cookie.setPath(path);
        cookieStore.addCookie(cookie);
    }


    /**
     * 把当前cookie从控制台输出出来
     *
     */
    public static void printCookies() {
        LOG.info("headers:");
        cookieStore = context.getCookieStore();
        List<Cookie> cookies = cookieStore.getCookies();
        for (Cookie cookie : cookies) {
            LOG.info("key:" + cookie.getName() + "  value:" + cookie.getValue());
        }
    }

    /**
     * 检查cookie的键值是否包含传参
     *
     * @param key
     * @return
     */
    public static boolean checkCookie(String key) {
        cookieStore = context.getCookieStore();
        List<Cookie> cookies = cookieStore.getCookies();
        boolean res = false;
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(key)) {
                res = true;
                break;
            }
        }
        return res;
    }

    public static void main(String[] args) throws Exception {

        //用户登陆
        Map<String,String> loginParam = new HashedMap();
        loginParam.put("loginId","baoyong");
        loginParam.put("passwd","qqq111");
        String  response = HttpClientKeepSession.post(
                "http://127.0.0.1:8080/xyre/enterpriseAdmin/dologin",
                loginParam);

        LOG.info(response);

       // printResponse(response);
        printCookies();



        Map<String,String> indexParam = new HashedMap();

           response = HttpClientKeepSession.post(
                "http://127.0.0.1:8080/xyre/enterpriseAdmin/get",
                loginParam);
        LOG.info(response);
        //上传数据
//        HttpClientKeepSession.upload("http://localhost:8080/BCP/all/test/upload");
//        printCookies();
    System.exit(0);
    }




}

 终于可以做session登录验证了。

分享到:
评论

相关推荐

    jshelleasy:VS Code Extension-使用Jshell实时编辑代码片段

    活动编辑器中的脚本发生更改后,代码将立即执行要求需要&gt; = JDK 9(jshell应该可以全局访问)用法ctl + shift + P或cmd + shift + P (Mac) 搜索JShell Easy - Start Session 或者只需使用键绑定ctl + shift + J...

    Java Web编程宝典-十年典藏版.pdf.part2(共2个)

    《Java Web编程宝典(十年典藏版)》适用于Java Web的初学者、编程爱好者,同时也可以作为培训机构、大中专院校老师和学生的学习参考用书。 目录 第1篇 技能学习篇 第1章 驾驭Ja垤Web开发环境 ——开启JavaWeb开发之...

    Session.docx

    可以写任意java代码 //获取用户名cookie Cookie[]cookies=request.getCookies(); Stringusername=""; if(cookies!=null){ for(Cookiec:cookies){ if("remname".equals(c.getName())){ username=c.getValue(); //解码...

    net学习笔记及其他代码应用

    26.根据委托(delegate)的知识,请完成以下用户控件中代码片段的填写: namespace test { public delegate void OnDBOperate(); public class UserControlBase : System.Windows.Forms.UserControl { public ...

    支持多数据库的ORM框架ef-orm.zip

    Session对象可以直接提供原本要Criteria API才能提供实现的功能。API大大简化。 IQueryableEntity允许你将一个实体直接变化为一个查询(Query),在很多时候可以用来完成复杂条件下的数据查询。比如 ‘in (?,?,...

    达内客户端+聊天室源码

    j++) {// 由于数据中还含有部分额外代码,遍历所有记录筛选数据 String msg = jilu[j];// 单条记录中的每一个数据 System.out.println(msg); msg = msg.substring(msg.lastIndexOf("&gt;") + 1, msg.length()...

    基于J2EE框架的个人博客系统项目毕业设计论文(源码和论文)

    而JSP的组件是用Java开发的,可以直接使用; 4、一次编写,处处运行:作为JAVA开发平台的一部分,JSP具有JAVA的所有优点,包括Write once , Run everywhere. 3.2. 数据库的选择 3.2.1. Web应用程序开发环境—SQL...

    freemarker总结

    JAVA模版引擎Freemarker常用标签(一) 1. if指令 这是一个典型的分支控制指令,该指令的作用完全类似于Java语言中的if,if指令的语法格式如下: &lt;#if condition&gt;... &lt;#elseif condition&gt;... &lt;#elseif condition&gt;......

    spring security 参考手册中文版

    活动目录错误代码 229 30. JSP标签库 230 30.1声明Taglib 230 30.2授权标签 230 30.2.1禁用测试的标签授权 231 30.3认证标签 232 30.4 accesscontrollist标签 232 30.5 csrfInput标签 233 30.6 csrfMetaTags标签 233...

    ZendFramework中文文档

    命名片段 7.9.4. 在响应对象中测试异常 7.9.5. 子类化响应对象 7.10. 插件 7.10.1. 简介 7.10.2. 编写插件 7.10.3. 使用插件 7.10.4. 获取和控制插件 7.10.5. 包含在标准发行包中的插件 7.10.5.1. 动作...

    JBoss Seam 工作原理、seam和hibernate的范例、RESTFul的seam、seam-gen起步、seam组件、配置组件、jsf,jboss、标签、PDF、注解等等

    Java EE 框架..................................................................................................................................................................................1 ...

Global site tag (gtag.js) - Google Analytics