Using cookies with HttpURLConnection

Before the advent of REST, we services were stateful. There were cookies sent with every HTTP request to maintain the state of the client using the services. When we use HttpURLConnection (Java) we need to discretely mention the cookies in the header and store it somewhere for maintaining the session. Below is an attempt using a singleton class for maintaining the session details and some sample HTTP methods:

First our Singleton to maintain the cookies in memory between successive transactions:

package singletonCookieManager;

import java.net.CookieManager;

/**
 * @author absin
 *
 */
public class EaqerInitializedCookieHelper {

private static final CookieManager instance = new CookieManager();

// private constructor to avoid client applications to use constructor
private EaqerInitializedCookieHelper() {
}

public static CookieManager getInstance() {
return instance;
}
}

Next, wherever you want to use this class initialize it as such

private static java.net.CookieManager msCookieManager = EaqerInitializedCookieHelper.getInstance();
private static final String COOKIES_HEADER = "Set-Cookie";

Next, have different methods to perform the reading and writing action of the cookies (Why?). You should also use URI  while reading cookies form the connection so as to maintain multiple cookies for different URLs.


private void readCookies(HttpURLConnection con) {
Map<String, List<String>> headerFields = con.getHeaderFields();
List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);

if (cookiesHeader != null) {
for (String cookie : cookiesHeader) {
try {
msCookieManager.getCookieStore().add(con.getURL().toURI(), HttpCookie.parse(cookie).get(0));
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

private void writeCookies(HttpURLConnection con) {
if (msCookieManager.getCookieStore().getCookies().size() > 0) {
// While joining the Cookies, use ',' or ';' as needed. Most of the servers are
// using ';'
String cookieText = "";
for (HttpCookie cookie : msCookieManager.getCookieStore().getCookies()) {
cookieText += cookie.getName() + "=" + cookie.getValue() + ";";
}
if (cookieText.length() > 1)
cookieText = cookieText.substring(0, cookieText.length() - 1);
System.out.println(cookieText);
con.setRequestProperty("cookie", cookieText);
}
}



Next attach these into your methods doing the Http calls as shown below. Note the timing of doing so you shouldn't read the headers before have added all hdeaders or you will get "Already Connected"exceptions. For more information refer https://github.com/absin1/TalentifyClient


public String sendGet(TestCase testCase, TestCaseResult caseResult) throws Exception {
String url = testCase.getUrl();
URL obj = new URL(url);
HttpURLConnection con = null;
con = (HttpURLConnection) obj.openConnection();
writeCookies(con);
con.setRequestMethod("GET");
// con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Content-Encoding", "gzip");
con.setConnectTimeout(100000000);
readCookies(con);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
caseResult.setUrl(testCase.getUrl());
caseResult.setStatus(responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
con.disconnect();
System.out.println(response.toString());
// caseResult.setResponseBody(response.toString());
return response.toString();
}

public String sendPost(TestCase testCase, HashMap<String, String> runtimes, TestCaseResult caseResult)
throws Exception {
URL obj = new URL(testCase.getUrl());
HttpURLConnection con = null;
con = (HttpURLConnection) obj.openConnection();
writeCookies(con);
con.setRequestMethod("POST");
// con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
String body = getBody(testCase, runtimes);
wr.writeBytes(body);
wr.flush();
wr.close();
readCookies(con);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + testCase.getUrl());
System.out.println("Post parameters : " + body);
System.out.println("Response Code : " + responseCode);
caseResult.setUrl(testCase.getUrl());
caseResult.setStatus(responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();

// print result
System.out.println(response.toString());
caseResult.setResponseBody(response.toString());
con.disconnect();
return response.toString();
}

public String sendPut(TestCase testCase, HashMap<String, String> runtimes, TestCaseResult caseResult)
throws Exception {
URL obj = new URL(testCase.getUrl());
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.connect();
writeCookies(con);
con.setRequestMethod("PUT");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setDoOutput(true);
readCookies(con);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
String body = getBody(testCase, runtimes);
wr.writeBytes(body);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'PUT' request to URL : " + testCase.getUrl());
System.out.println("Post parameters : " + body);
System.out.println("Response Code : " + responseCode);
caseResult.setUrl(testCase.getUrl());
caseResult.setStatus(responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
caseResult.setResponseBody(response.toString());
con.disconnect();
return response.toString();

}

Comments

Popular posts from this blog

SPARQL

ffmpeg for Google Speech API