Skip to content

Handle Cookies

Chirag Jayswal edited this page May 15, 2019 · 2 revisions

Below is the example of easiest way to handle cookies automatically using HttpClient's default cookie policy. It uses ApacheHttpClient. You need to register class using rest.client.impl property. For example:

rest.client.impl=qaf.example.listener.ClientWithSessionManagenent

ClientWithSessionManagenent.java

package qaf.example.listener;

import org.apache.commons.httpclient.HttpClient;

import com.qmetry.qaf.automation.ws.rest.RestClientFactory;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandler;
import com.sun.jersey.client.apache.ApacheHttpClient;
import com.sun.jersey.client.apache.ApacheHttpClientHandler;
import com.sun.jersey.client.apache.config.ApacheHttpClientConfig;
import com.sun.jersey.client.apache.config.DefaultApacheHttpClientConfig;

/**
 * To handle coockies, register this class using <code>rest.client.impl</code> property as below:
 * <p>
 * <code>rest.client.impl=qaf.example.listener.ClientWithSessionManagenent</code>
 * @author chirag.jayswal
 *
 */
public class ClientWithSessionManagenent extends RestClientFactory {

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.qmetry.qaf.automation.ws.rest.RestClientFactory#createClient()
	 */
	@Override
	protected Client createClient() {
		HttpClient httpClient = new HttpClient();
		ApacheHttpClientConfig config = new DefaultApacheHttpClientConfig();
		config.getProperties().put(ApacheHttpClientConfig.PROPERTY_HANDLE_COOKIES, true);
		// ApacheHttpClient httpClient = ApacheHttpClient.create(config);
		ApacheHttpClientHandler clientHandler = new ApacheHttpClientHandler(httpClient, config);
		ClientHandler root = new ApacheHttpClient(clientHandler);

		Client client = new Client(root, config);
		return client;
	}

}

Note: Make sure that you have qaf-support-ws dependency added in your project.

Clone this wiki locally