Contact Rao
Contact Rao

Reputation: 69

Send cookies over HTTPURLConnection

I am trying use the HTTPURLConnection class to open connection to a JSP and receive a response from a servlet. A response header is set in the JSP that need to be read in the servlet.

The code sample is as below

String strURL = "http://<host>:<port>/<context>/mypage.jsp";
String sCookies = getCookie();//method to get the authentication cookie(**SSOAUTH**) and its value for the current logged in user

URL url = new URL(strURL);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestProperty("Cookie", URLEncoder.encode(sCookies, "UTF-8"));
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);

DataOutputStream out = new DataOutputStream(urlConnection.getOutputStream());
out.writeBytes("lang=en");
out.flush();
out.close();

 //reading the response received from JSP and retrieve header value
response.write(urlConnection.getHeaderField("commAuth") + "<br />");

The issue is the passed SSOAUTH cookie is not sent to the JSP. If I send the UID/PWD instead of cookie as below the authentication succeeds and response is sent correctly.

urlConnection.setRequestProperty("username", "testuser");
urlConnection.setRequestProperty("password", "testpwd");

Is this the right way of sending cookie over HTTPURLConnection? or are there other parameters that need to be set?

Upvotes: 3

Views: 5682

Answers (1)

jcern
jcern

Reputation: 7848

You may want to try removing the URLEncoder.encode from the entire sCookies String. The cookie format should be in the form of NAME=VALUE, but by URLEncoding the whole string you will escape the =.

Upvotes: 2

Related Questions