简体   繁体   English

尝试使用HttpClient设置会话cookie

[英]Trying setting session cookie using HttpClient

Help setting cookie to HttpClient 帮助将cookie设置为HttpClient

Created a program which logins to an external web service. 创建了一个登录外部Web服务的程序。 However, to obtain vital information from an HTTP GET, I am unable to pass in the cookie (generated from the login). 但是,要从HTTP GET获取重要信息,我无法传入cookie(从登录生成)。

public class ClientHelper {
    private final static String PROFILE_URL = 
                               "http://externalservice/api/profile.json";
    private final static String LOGIN_URL = "http://externalservice/api/login";

    public static Cookie login(final String username, final String password) {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(LOGIN_URL);
        HttpContext localContext = new BasicHttpContext();
        client.getParams().setParameter("http.useragent", "Custom Browser");
        client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, 
                                        HttpVersion.HTTP_1_1);
        List<Cookie> cookies = null;
        BasicClientCookie cookie = null;

        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
            nameValuePairs.add(new BasicNameValuePair("user", username));
            nameValuePairs.add(new BasicNameValuePair("passwd", password));
            UrlEncodedFormEntity entity = 
                    new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8);
            entity.setContentType("application/x-www-form-urlencoded");

            post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = client.execute(post, localContext);
            cookies = client.getCookieStore().getCookies();
            System.out.println(cookies.get(1));

            cookie = new BasicClientCookie(cookies.get(1).getName(), cookies.get(1).getValue());
            cookie.setVersion(cookies.get(1).getVersion());
            cookie.setDomain(cookies.get(1).getDomain());
            cookie.setExpiryDate(cookies.get(1).getExpiryDate());
            cookie.setPath(cookies.get(1).getPath());               
            BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            String line = "";
            while ((line = rd.readLine()) != null) {
                System.out.println(line);
            }
        } 
        catch (Throwable e) {
            e.printStackTrace();
        }
        return cookie;
   }

   public static void getProfile(Cookie cookie) {
      DefaultHttpClient client = new DefaultHttpClient();
      HttpContext context = new BasicHttpContext();
      CookieStore cookieStore = new BasicCookieStore();
      cookieStore.addCookie(cookie);
      client.setCookieStore(cookieStore);
      context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
      HttpGet get = new HttpGet(PROFILE_URL);
      HttpResponse response;

      try {
          response = client.execute(get, context);
          BufferedReader rd = 
             new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent()));

          String line = "";
          while ((line = rd.readLine()) != null) {
              System.out.println(line);
          }
       } 
       catch (ClientProtocolException e) {
           e.printStackTrace();
       } 
       catch (IOException e) {
           e.printStackTrace();
       }
   }
}

App.java (class that uses ClientHelper): App.java(使用ClientHelper的类):

public class App {
   private static final String USER = "myusername";
   private static final String PASSWD = "mypassword";

   public static void main(String[] args) {
       Cookie cookie = ClientHelper.login(USER, PASSWD);
       ClientHelper.getProfile(cookie);
   }
}

When I run App, I am able to login (I see the generated JSON) but the getProfile() method returns an empty JSON object: 当我运行App时,我能够登录(我看到生成的JSON),但getProfile()方法返回一个空的JSON对象:

 {}

From the command line, using curl I am trying to emulate this: 从命令行,使用curl我试图模仿这个:

curl -b Cookie.txt http://externalservice/api/profile.json

This actually works but not my Java program. 这实际上有效,但不是我的Java程序。

Try by executing this part of the code: 尝试执行这部分代码:

List<Cookie> cookies = client.getCookieStore().getCookies();
        for (Cookie cookie : cookies) {
             singleCookie = cookie;
        }

After

 HttpResponse response = client.execute(post, localContext);

After changing your code to get the cookies after the login request, you actually are getting all the cookies from the request. 更改代码以在登录请求后获取cookie后,您实际上是从请求中获取所有cookie。

I suspect the problem is that whatever Cookie it is at index 1 in the CookieStore isn't the one you need, and obviously since it's not throwing an IndexOutOfBounds exception when you do that, there's at least one other Cookie in there (at index 0 ). 我怀疑问题是它在CookieStore中的索引1处的Cookie不是你需要的那个,显然因为当你这样做时它没有抛出IndexOutOfBounds异常,那里至少有一个其他Cookie (在索引0 )。 Return the list of cookies and send all of them with your profile request. 返回Cookie列表并将其全部发送给您的个人资料请求。

Taking your code, changing all those indexes from 1 to 0 and pointing at this simple PHP script shows that it is receiving then sending the cookies: 获取代码,将所有索引从1更改为0并指向此简单的PHP脚本,表明它正在接收然后发送cookie:

<?php
    setcookie("TestCookie", "Some value");
    print_r($_COOKIE);        
?>

output: 输出:

[version: 0][name: TestCookie][value: Some+value][domain: www.mydomain.org][path: /][expiry: null]
Array
(
)
Array
(
    [TestCookie] => Some value
)

I figured it out... I was creating two different HTTP clients instead of using the same one. 我想通了......我正在创建两个不同的HTTP客户端而不是使用相同的HTTP客户端。

@Brian Roach & Raunak Agarwal thank you both very much for the help! @Brian Roach和Raunak Agarwal非常感谢你们的帮助!

Here's the fix: 这是修复:

public static HttpClient login(final String username, final String password) 
{
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(LOGIN_URL);
    client.getParams().setParameter("http.useragent", "Custom Browser");
    client.getParams().setParameter(
             CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    try 
    {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
        nameValuePairs.add(new BasicNameValuePair("user", username));
        nameValuePairs.add(new BasicNameValuePair("passwd", password));
        UrlEncodedFormEntity entity = 
              new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8);
        entity.setContentType("application/x-www-form-urlencoded");

        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = client.execute(post);

        BufferedReader reader = 
              new BufferedReader(
              new InputStreamReader(response.getEntity().getContent()));

        String line = "";
        while ((line = reader.readLine()) != null) 
        {
            System.out.println(line);
        }
    } 
    catch (Throwable e) { e.printStackTrace(); }
    return client;
}

public static void getProfile(HttpClient client) 
{
    HttpGet get = new HttpGet(PROFILE_URL);
    HttpResponse response;
    try 
    {
        response = client.execute(get);
        BufferedReader reader = 
               new BufferedReader(
               new InputStreamReader(response.getEntity().getContent()));

        String line = "";
        while ((line = reader.readLine()) != null) 
        {
            System.out.println(line);
        }
    } 
    catch (ClientProtocolException e) { e.printStackTrace(); } 
    catch (IOException e) { e.printStackTrace(); }  
}

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

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