Reputation: 361
I'm having kind of a problem with the 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. I tried it using the classes provided by java, but there I got thrown back to the login page every time. It seems to work with the Apache client, but I tried to remove all the cookie handling code to see if it still works. 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. 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. 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);
Upvotes: 2
Views: 4951
Reputation: 21
My English is poor. The cookies are actually coming from CookieStore.But the cookies aren't operated in execute(HttpUriRequest request). If you want add or remove cookies.you can use execute(HttpUriRequest request, HttpContext context) . 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();
}
}
Upvotes: 2