繁体   English   中英

Java HttpClient:即使我已经成功登录,当我请求其他网页时,我仍会返回登录页面

[英]Java HttpClient: I keep getting login page back when I request a different webpage even after I had already logged in successfully

我的目标:

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

至今:

  • 我通过HttpPost登录并保存cookie:

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:


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;
}
.....  
  • 我发送一个获取请求:

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;
}
  • 我得到的响应是登录页面:

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;
}
......

我为什么得到这个? 我什至可以看到我发送的请求是与登录名相同的会话。 有人遇到过这个问题吗? 有人想出解决方案吗?

谢谢。

我也有类似的经历。 cookie可能会被HttpClient拒绝。 我用以下代码解决了它:

        ...

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

        ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM