向 HTTP 请求添加 Cookie


Adding a cookie to a HTTP request

>我正在尝试添加一个带有 GUID 的 cookie 来识别用户,但是当我在测试脚本上运行它时,我的代码似乎没有发送任何 cookie。

我的 Java 代码:

    public void search(String q, int o) {
    final String query = q;
    final int offset = o;
    Thread searchThread = new Thread() {
        public void run() {
            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                BasicHttpContext httpContext = new BasicHttpContext();
                CookieStore cookieStore = new BasicCookieStore();
                httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
                cookieStore.addCookie(new BasicClientCookie("remixsid", guid));
                httpClient.setCookieStore(cookieStore);
                HttpPost httpPost = new HttpPost("http://192.168.1.43/test/test.php?section=audio&q=" + URLEncoder.encode(query, HTTP.UTF_8) + "&offset=" + offset);
                //HttpPost httpPost = new HttpPost("http://vkontakte.ru/gsearch.php?section=audio&q=" + URLEncoder.encode(query, HTTP.UTF_8) + "&offset=" + offset);
                HttpResponse response = httpClient.execute(httpPost, httpContext);
                String responseBody = EntityUtils.toString(response.getEntity());
                System.out.print(responseBody);
            } catch(Exception e) {
                System.out.println(e.toString());
            }
        }
    };
    searchThread.run();
}

我的PHP代码来测试饼干:

<?php
$cookies = $_COOKIE;
if(!count($cookies) > 0)
    echo 'No cookies!';
foreach ($cookies as $key=>$val)
    echo "$key--> $val";
?>

使用以下代码检索 GUID:

    public void login(String usr, String pass) {
    logout();
    final String username = usr;
    final String password = pass;
    Thread loginThread = new Thread() {
        public void run() {
            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost("http://login.vk.com/?act=login&email=" + URLEncoder.encode(username, HTTP.UTF_8) + "&pass=" + URLEncoder.encode(password, HTTP.UTF_8));
                httpClient.execute(httpPost);
                List<Cookie> cookies = httpClient.getCookieStore().getCookies();
                for(Cookie cookie : cookies) {
                    System.out.println("Cookie: " + cookie.toString());
                    if(cookie.getName().contains("remixsid"))
                        guid = cookie.getValue();
                }
            } catch(Exception e) {
                System.out.println(e.toString());
                System.out.println("An error occured");
                if(loginHandler != null)
                    loginHandler.onLoginError(e);
                return;
            }
            if(!isLoggedIn()) {
                System.out.println("User credentials invalid");
                if(loginHandler != null)
                    loginHandler.onLoginInvalidCredentials();
                return;
            }
            if(loginHandler != null)
                loginHandler.onLoginSuccess();
            System.out.println("Login successfull GUID is: " + guid);
        }
    };
    loginThread.start();
}

手动设置 cookie 标头似乎有效...

    public void search(String q, int o) {
    final String query = q;
    final int offset = o;
    Thread searchThread = new Thread() {
        public void run() {
            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost("http://192.168.1.43/test/test.php");
                //HttpPost httpPost = new HttpPost("http://vkontakte.ru/gsearch.php?section=audio&q=" + URLEncoder.encode(query, HTTP.UTF_8) + "&offset=" + offset);
                httpPost.setHeader("Cookie", "remixsid=" + guid);
                HttpResponse response = httpClient.execute(httpPost);
                String responseBody = EntityUtils.toString(response.getEntity());
                System.out.println(responseBody);
            } catch(Exception e) {
                System.out.println(e.toString());
            }
        }
    };
    searchThread.start();
}

几点意见和建议:

  1. 您没有向 Cookie 添加任何路径信息。您可以使用BasicClientCookie.setPath()方法。
  2. 尝试读取此cookie的php脚本的路径是什么?
  3. 当 cookie 设置在根路径/ ) 时,则只有它可供所有其他服务器端程序使用。
  4. 将 cookie 的路径设置为 root,或者使 cookie 的路径与 PHP 脚本的路径相同。

编辑:

我错过了域部分。您还需要设置 Cookie 域。假设你的 PHP 脚本运行在 http://mysite/myscript.php 这里mysite是域(如果你在本地盒子上运行脚本,可能会localhost)。使用 BasicClientCookie.setDomain() 设置 Cookie 域。

要理解这一点,假设您的 http-client lib 是与网站交互的浏览器。浏览器存储来自许多站点的 Cookie,但在向特定站点发出请求时,它仅发送从该特定站点收到的 Cookie。

如果未设置域,则库不会将 cookie 发送到该主机。