URLConnection
Send cookie with HTTP request
This is an example of how to send a cookie with an HTTP request in Java. In short, to send cookies with HTTP requests one should :
- Create a URL Object that represents the resource you want to access
- Use the
openConnection()
API method of the URL Object to access connection specific parameters for the HTTP request - Use the
setRequestProperty()
API method from the connection Object to set a Name-Value pair representing the cookie to be used for the specific HTTP request. You can set several Name-Value pairs as the value of the specific cookie separated by semi-colons
as shown in the code snippet below.
package com.javacodegeeks.snippets.core; import java.net.URL; import java.net.URLConnection; public class SendCookieWithHTTPRequest { public static void main(String[] args) throws Exception { URL url = new URL("http://www.google.com:80"); URLConnection conn = url.openConnection(); // Set the cookie value to send conn.setRequestProperty("Cookie", "name1=value1; name2=value2"); // Send the request to the server conn.connect(); } }
This was an example of how to send cookies with HTTP requests in Java.