I was trying to get a certain page through java, but with this page I didn't succeed.
Now in my browser it does work, but when I disable Cookies in the settings, it doesn't anymore.
So I probably need to add cookies to my post request in java.
So I went searching the interwebs, but unfortunately I couldn't really find anything useful. mostly it was vague, scattered or irrelevant.
So now my question :
Could anyone show me how to do it (mentioned above^^), or point me to a clear site?
To send cookies to the server, you need to add the "Cookie: name=value" header to your request. To send multiple Cookies in one cookie header, you can separate them with semicolons. In this Send Cookies example, we are sending HTTP cookies to the ReqBin echo URL.
To add cookies to a request for authentication, use the header object that is passed to the get/sendRequest functions. Only the cookie name and value should be set this way. The other pieces of the cookie (domain, path, and so on) are set automatically based on the URL the request is made against.
To add a new cookie, use HttpServletResponse. addCookie(Cookie). The Cookie is pretty much a key value pair taking a name and value as strings on construction.
Java Cookie Example You can write cookies using the HttpServletResponse object like this: Cookie cookie = new Cookie("myCookie", "myCookieValue"); response. addCookie(cookie); As you can see, the cookie is identified by a name, " myCookie ", and has a value, " myCookieValue ".
Here's a simple example of setting a cookie in a POST request with URLConnection
:
URL url = new URL("http://example.com/");
String postData = "foo bar baz";
URLConnection con = url.openConnection();
con.setDoOutput(true);
con.setRequestProperty("Cookie", "name=value");
con.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
con.connect();
OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
out.write(postData);
out.close();
You probably need to pass a cookie from a previous request, see this answer for an example. Also consider using Apache HttpClient to make things easier.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With