简体   繁体   English

Apache HTTP Client中的Cookie - Java

[英]Cookies in Apache HTTP Client - Java

I'm having kind of a problem with the Apache httpclient for Java. 我遇到了Apache httpclient for Java的问题。 I'm writing a login bot for a website, which extracts all the fields from the login forms, fills in username and password and logs into the account by making a POST request. 我正在为一个网站编写一个登录机器人,它从登录表单中提取所有字段,填写用户名和密码,并通过发出POST请求登录到帐户。 I tried it using the classes provided by java, but there I got thrown back to the login page every time. 我尝试使用java提供的类,但每次都被扔回登录页面。 It seems to work with the Apache client, but I tried to remove all the cookie handling code to see if it still works. 它似乎与Apache客户端一起工作,但我试图删除所有cookie处理代码,看它是否仍然有效。 I no longer save cookies in a list and I don't add cookies to the request, but it seems that I'm still getting logged in correctly. 我不再将cookie保存在列表中,并且我不会在请求中添加cookie,但似乎我仍然正在登录。 How can that be? 怎么可能? I don't use a cookiestore and I don't know where the cookies are coming from, so obviously they must be saved somewhere in the background. 我不使用cookiestore而且我不知道cookie的来源,所以很明显它们必须保存在后台的某个地方。 I need to clear them to start a new session. 我需要清除它们才能开始新的会话。 I create the client like this 我像这样创建客户端

    CloseableHttpClient client = HttpClients.createDefault();

and make requests like this 并提出这样的要求

HttpPost post = new HttpPost(url+"/login");
HttpResponse response = client.execute(post);

My English is poor. 我的英文程度不高。 The cookies are actually coming from CookieStore.But the cookies aren't operated in execute(HttpUriRequest request). Cookie实际上来自CookieStore.But cookie不在execute(HttpUriRequest请求)中运行。 If you want add or remove cookies.you can use execute(HttpUriRequest request, HttpContext context) . 如果要添加或删除cookie。您可以使用execute(HttpUriRequest请求,HttpContext上下文)。 eg: 例如:

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;

/**
 * Created by y.wang on 11/16/16.
 */
public class HttpClientTest {
    public static void main(String[] args){
        CloseableHttpClient client = HttpClients.createDefault();
        HttpClientContext httpClientContext = new HttpClientContext();
        String url = "";
        HttpPost post = new HttpPost(url + "/login");
        try {
            HttpResponse response = client.execute(post, httpClientContext);
        } catch (IOException e) {
            e.printStackTrace();
        }
        httpClientContext.getCookieStore().clear();
    }
}

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

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