Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add cookies in a post request in Java?

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?

like image 229
78978909 Avatar asked Apr 30 '11 22:04

78978909


People also ask

How do I set cookies in a post request?

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.

How do I add a cookie to a GET request?

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.

How do you add cookies to a response?

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.

How do you declare cookies in Java?

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 ".


1 Answers

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.

like image 133
WhiteFang34 Avatar answered Sep 29 '22 14:09

WhiteFang34