Home » Core Java » net » URLConnection » Send cookie with HTTP request

About Ilias Tsagklis

Ilias Tsagklis
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

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.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of