HttpClient模拟登陆如何获取cookies

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

3个回答

    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();
    }

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

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐