oCrackMe
oCrackMe
采纳率100%
2017-03-30 04:32 阅读 2.1k
已采纳

HttpClient模拟登陆如何获取cookies

我在java web开发时候 尝试使用HttpClient post模拟登陆,可是无法获取到登陆的cookie
,之前在安卓开发时候Xutil可以直接获取,那么在WEB开发时候如何解决获取cookie的问题

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

3条回答 默认 最新

  • 已采纳
    lovingjiajia kikisang 2017-03-30 06:53
        CookieStore cookieStore = new BasicCookieStore();
        HttpClientContext localContext = new HttpClientContext();
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost("http://xxx.net/loign.jsp");
        localContext.setCookieStore(cookieStore);
        httppost.setHeader("Content-Type", "text/html; charset=utf-8");
        List<NameValuePair> formParams = new ArrayList<NameValuePair>();
        formParams.add(new BasicNameValuePair("username", "username"));
        formParams.add(new BasicNameValuePair("password", "password"));
        try {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8");
            httppost.setEntity(entity);
            // 提交登录数据
            HttpResponse re = httpclient.execute(httppost, localContext);
            // 获取cookie
            List<Cookie> cookies = cookieStore.getCookies();
            for (Cookie cookie : cookies) {
                System.out.println("Local Cookie:" + cookie);
            }
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
    点赞 1 评论 复制链接分享
  • oyljerry oyljerry 2017-03-30 04:50
  • oCrackMe oCrackMe 2017-03-30 07:01

    感谢。了解通过模拟表单提交来实现

    点赞 评论 复制链接分享

相关推荐