首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java HttpClient:即使在我已经成功登录之后,当我请求一个不同的网页时,我仍然会重新获得登录页面。

Java HttpClient:即使在我已经成功登录之后,当我请求一个不同的网页时,我仍然会重新获得登录页面。
EN

Stack Overflow用户
提问于 2015-06-04 16:01:12
回答 1查看 1.4K关注 0票数 1

我的目标是:

  • 后登录
  • 在同一会话中获取图像(链接)并将其发布

迄今为止:

  • 我通过HttpPost登录并保存cookie:
代码语言:javascript
复制
private String sessionId = ""; 


....

private int loginToServer() throws IOException
{
    int result = 0;
    String httpsURL = "http://192.168.1.100:8080/foo/login.jsp";
    HttpResponse response;
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpClientContext httpContext = HttpClientContext.create();
    try 
    {

        HttpPost httpPost = new HttpPost(httpsURL);
        List <NameValuePair> nvps = new ArrayList <NameValuePair>();

        nvps.add(new BasicNameValuePair("username", "*****"));
        nvps.add(new BasicNameValuePair("password", "*****"));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        response = httpclient.execute(httpPost,httpContext);

        //store cookies
        CookieStore cookieStore = new BasicCookieStore();
        cookieStore = httpContext.getCookieStore();
        List<Cookie> cookies = cookieStore.getCookies();
        if(cookies != null)
        {
            for(Cookie cookie : cookies)
            {
               sessionId = cookie.getValue();                   
            }
        }
        result = response.getStatusLine().getStatusCode();
        System.out.println(response.getStatusLine());

        HttpEntity entity = response.getEntity();
        EntityUtils.consume(entity);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } 

    return result;
}
  • 我得到HTTP/1.1 200 OK:
代码语言:javascript
复制
POST /mysubdir/login.jsp HTTP/1.1

Content-Length: 33

Content-Type: application/x-www-form-urlencoded
Host: 192.168.2.100:8080
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.4.1 (Java/1.8.0_25)
Accept-Encoding: gzip,deflate

username=******&password=******HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=97D93F7C7E11F22A6E895554E761D3AE; Path=/foo/;    HttpOnly
Content-Type: text/html;charset=ISO-8859-1
Transfer-Encoding: chunked
Date: Thu, 04 Jun 2015 13:21:18 GMT

2000

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Hoarder Login</title>
<link rel="icon" href="resource/favicon.ico"></link>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
<style type='text/css'>
html, body {
 .margin: 0;
 .padding: 0;
 .overflow: hidden;
}
.....  
  • 我发送了一个Get请求:
代码语言:javascript
复制
private InputStream sendGet(String url) {
    System.out.println("\nSending 'GET' request to URL : " + url);
    HttpGet httpGet = new HttpGet(url);

    HttpResponse response  = null;
    InputStream is = null;
    try 
    {

        //Setting up cookie store
        CookieStore cookiestr = new BasicCookieStore(); 
        BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", sessionId);
        cookie.setDomain("192.168.1.100");
        cookie.setPath("/foo/");
        cookie.setAttribute(ClientCookie.PATH_ATTR, "/foo/");
        cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "192.168.1.100");


        CookieStore cookiestr = httpContext.getCookieStore();
        cookiestr.addCookie(cookie);
        httpContext.setCookieStore(cookiestr);

    CloseableHttpClient httpclient =  HttpClients.custom().setDefaultCookieStore(cookiestr).build();

        httpclient = HttpClients.createDefault();
        response = httpclient.execute(httpGet); 
        is = response.getEntity().getContent();

        System.out.println("Response Code : " + response.getStatusLine());
        EntityUtils.consume(response.getEntity());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return is;
}
  • 我得到的响应是登录页面:
代码语言:javascript
复制
GET /foo/images/B0DF3A14706A-008-0008/7.jpg HTTP/1.1
Host: 192.168.1.100:8080
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.4.1 (Java/1.8.0_25)
Cookie: JSESSIONID=97D93F7C7E11F22A6E895554E761D3AE
Accept-Encoding: gzip,deflate

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Cache-Control: private
Expires: Wed, 31 Dec 1969 19:00:00 EST
Set-Cookie: JSESSIONID=D94C9147870EE8A7DEEDB67AD77B695E; Path=/foo/;     HttpOnly
Content-Type: text/html;charset=ISO-8859-1
Transfer-Encoding: chunked
Date: Wed, 03 Jun 2015 18:28:02 GMT

2000

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head>
<title>Hoarder Login</title>
<link rel="icon" href="resource/favicon.ico"></link>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
<style type='text/css'>
html, body {
 .margin: 0;
 .padding: 0;
 .overflow: hidden;
}
......

我为什么要得到这个?我甚至可以看到,我发送的请求与登录的会话相同。有人有这个问题吗?有谁想出解决办法了吗?

谢谢。

EN

回答 1

Stack Overflow用户

发布于 2015-06-10 19:53:26

我也有过类似的经历。cookie可能会被HttpClient拒绝。我用下面的代码解决了这个问题:

代码语言:javascript
复制
        ...

        CookieSpecProvider easySpecProvider = new CookieSpecProvider() {

            public CookieSpec create(HttpContext context) {

                return new BrowserCompatSpec() {
                    @Override
                    public void validate(Cookie cookie, CookieOrigin origin)
                            throws MalformedCookieException {
                        // Oh, I am easy
                    }
                };
            }

        };

        registry = RegistryBuilder.<CookieSpecProvider>create()
                .register("easy", easySpecProvider)
                .build();

        closableClient = httpclient.setDefaultCookieSpecRegistry(registry).setDefaultRequestConfig(httpRequestBase.getConfig()).build();

        response = closableClient.execute(httpRequestBase, context);

        ...
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30648734

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档