Thursday 18 April 2019

How to send Cookies from Web(GUI) to Web Service


Cookies: Browser Cookies are also referred as Internet Cookie,Web Cookie or HTTP Cookie. A cookie is a "small piece of data" sent from the website to the user's device while the user is accessing the website.
There are multiple ways these cookies are being used in modern world like authentication, browser state information, storing user personal information like name, address etc., tracking the user activity on web, etc., Different types of cookies satisfy different needs.

In certain cases, one might have to test web services which needs cookies to be passed as part of request. One way to address this, is to combine Web application plus web service test steps. 

Below code snippet would open the web application, capture the cookies stored by the application and pass it to web service using Rest Assured.


public class CookiesToWebServices {
static WebDriver driver;
static String driverPath = "C:/Drivers/chromedriver.exe";

public static void main(String[] args) {

System.setProperty("webdriver.chrome.driver",driverPath);
ArrayList cookieList = new ArrayList();

String url = "www.testurl.com/testpath/id";
HashMap headermap = new HashMap<>();
headermap.put("Content-Type", "application/json");
headermap.put(....

HashMap queryParammap = new HashMap<>();
queryParammap.put("id", "12345");
queryParammap.put(....


//Open the desired website & navigate to required page(if required)
driver = new ChromeDriver();
driver.get("https://www.amazon.in/");
driver.manage().window().maximize();
driver.navigate().to("https://www.amazon.in/gp/goldbox?ref_=nav_topnav_deals");

//Get the cookies from web
Set<Cookie> SeCookies = driver.manage().getCookies();

//Iterate the web cookies into RestAssured cookie list
for(Cookie ck : SeCookies){
cookieList.add(new io.restassured.http.Cookie.Builder(ck.getName(), ck.getValue()).build());
}

//Pass the cookie list to web request
Response response = RestAssured.given().log().all().headers(headermap).queryParams(queryParammap).cookies(new Cookies(cookieList)).get(url);

}
}



References: 
https://github.com/rest-assured/rest-assured/wiki/Usage
https://github.com/rest-assured/rest-assured/issues/911


2 comments:

  1. Thankyou for the information.Livewire Technologies is actively engaged in the autonomous driving space. Over the years, we have developed experience in Data Collection & Staging, Labeling & Annotation, and ADAS support.

    ReplyDelete