Java Http Client, passing it session id

Hi

I have an HTTP Client, that connects to an https site.
1. I cannot use any sophisticated HTTPClient class.
2. I have to set header User-Agent which contains a session ID
3. This code runs fine when i remove line 3, but we need to pass this session ID so that line is a must.
4. Keeping both line 2 and 3 gives http error staus code 409
5. removing line 2 gives  http error staus code 401

I think we have to enable cookies, and enable redirect. While keeping line 2 and line 3.

Please advise and provide some sample code. Thanks

public HttpsURLConnection getInformHttpConnection( String sessionTicket,  String userId,  String host, String page) throws Exception
{
  Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
  System.out.println("Connecting https://somesite.com");
  URL url = new URL("https",host,page);
  Authenticator.setDefault (new MyAuthenticator ()); //line 2
  con = (HttpsURLConnection) url.openConnection();
  con.setDoInput(true);
  con.setDoOutput(true);
  con.setRequestMethod("GET");
  con.setUseCaches(false);
  String headerData = createUserAgentHeader(sessionTicket,userId);
  con.setRequestProperty("User-Agent",headerData); //line 3
  java.io.BufferedReader rd = new java.io.BufferedReader( new java.io.InputStreamReader( con.getInputStream() ));
  String line;
      for( int i = 0; i < 11; i++)
      rd.readLine();
      while( (line = rd.readLine()) != null )
                      System.out.println( line );
      rd.close();
      return con;
}

format77Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

sompol_kiatkamolchaiCommented:
>>removing line 2 gives  http error staus code 401
401 is Unauthorized request the client should send a suitable Authorization header so line 2 is a must
>>This code runs fine when i remove line 3, but we need to pass this session ID
>>con.setRequestProperty("User-Agent",headerData); //line 3
why did you pass session ID by this code?
I think User-Agent is used for sending client program infomation such as product name,version.
(http://www.w3.org/Protocols/HTTP/HTRQ_Headers.html#user-agent)

If you want to pass session id, I think you should set it as cookie.
0
format77Author Commented:
Hi again

Yes, I am using User-Agent to pass session id (its a sort of token number not sure what logic is servlet implementing to handle it), product name, version and stuff like that. So its required.

Frankly, they were using HttpClient package before, now they want all implementation by classes provided by Sun. So I have no access to change the design and server side logic. Probably (though strange) session id is being parsed from User-Agent on server side.

Anyhow, lets assume that the only information being send through User-Agent is version and product info.  Does this make any difference?

How can we enable client to accept cookies ??????

And how do we pass information through cookies?????


0
objectsCommented:
Ask the server admins the reason for the 409, should give you a clue to the problem.

Sun's HTTP code aint the best though (which is why other implementations exist), what version are you running?
0
Introducing Cloud Class® training courses

Tech changes fast. You can learn faster. That’s why we’re bringing professional training courses to Experts Exchange. With a subscription, you can access all the Cloud Class® courses to expand your education, prep for certifications, and get top-notch instructions.

format77Author Commented:
Hi

I am using 1.4.2

0
objectsCommented:
maybe worth trying 1.5 to see if Sun have made any improvements.
0
sompol_kiatkamolchaiCommented:
The error 409 is HTTP Conflict.

There is some conflict in http request. I guess that it is caused by set property "User-Agent" in the wrong format. So try to send a simple User-Agent by the following format

User-Agent:
=======
This line if present gives the software program used by the original client. This is for statistical purposes and the tracing of protocol violations. It should be included. The first white space delimited word must be the software product name, with an optional slash and version designator. Other products which form part of the user agent may be put as separate words.

        <field>   =   User-Agent: <product>+
        <product> =   <word> [/<version>]
        <version> =   <word>
Example:
               User-Agent:  LII-Cello/1.0  libwww/2.5


Refer to http://www.w3.org/Protocols/HTTP/HTRQ_Headers.html#user-agent

0
girionisCommented:
Can you not pass the session id through a post method?
0
Venci75Commented:
try to replace line 3 with this one:
con.setRequestProperty("Cookie",headerData); //line 3
0
format77Author Commented:
Hi

In response to  sompol_kiatkamolchai comment, yes a simpler version does work. e.g.
con.setRequestProperty("User-Agent","Inform/53.42 [iecc]") works
while
con.setRequestProperty("Inform/53.42 [iecc] (Software Distribution/2.0; UA-TKT=ED24C6BB!j7cgMuTW4TESB0934STE!ASPCSC1!SFD)")
I have no idea why they are passing all this information, maybe its a token number

In repose to girionis comment
Is there some specific seesion id header that i need to set on client side, before sending request, that will automatically tell server that this is the session id or token number (these two are different). Because we cannot change server program.

In respone to Venci75 comment
Yes this works too, but does it has the same effect. Or it depends on how server interprets it.

Reminding guys that our communication interface should remain the same. As i told you the same thing was working when we were using HttpClient package.





 
0
girionisCommented:
>Is there some specific seesion id header that i need to set on client side, before sending
>request, that will automatically tell server that this is the session id or token number (these
>two are different). Because we cannot change server program.

No. My idea is based on sending the stream of data by using the output stream of the conenction. The receiving end shopuld have a way of identifying what the session id is (perhaps by sending the length of the data).
0
Venci75Commented:
The servers support sessions by passing their IDs using cookies or URLs.
It is very strange (for me) that the session id could be passed as User-Agent header. This in my opinion could be something specific to the server or to the used application.
The format of string, which is passed in the Cookie header is also serevr specific.
To archieve something similar to cookies support in the Sun's http client - always check whether the server response contains Set-Cookie header. If yes - set this value as a Cookie header in the subsequent requests.
0
format77Author Commented:
I am looking into the matter with people who designed the server, (I will keep you posted on that)to see how they are handling User-Agent. In the meantime. I have modified the User-Agent to be simple one, and there is another interesting issue coming up

public HttpsURLConnection getInformHttpConnection( String sessionTicket,  String userId,  String host, String page) throws Exception
{
  Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
  System.out.println("Connecting https://somesite.com");
  URL url = new URL("https",host,page);
  Authenticator.setDefault (new MyAuthenticator ()); //line 2
  con = (HttpsURLConnection) url.openConnection();
  con.setDoInput(true);
  con.setDoOutput(true);
  con.setRequestMethod("GET");
  con.setUseCaches(false);
  String headerData = createUserAgentHeader(sessionTicket,userId);
  con.setRequestProperty("User-Agent","Inform/53.42 [iecc]"); //line 3
return con ; //return HTTP Connection
  }


public static void main (String args[])
{
  try
  {
     HttpsURLConnection con = new CodeB1().getInformHttpConnection ("tokenid","id","serverName", "page");
     java.io.BufferedReader rd = new java.io.BufferedReader( new java.io.InputStreamReader( con.getInputStream() ));
      String s = con.getRequestProperty("User-Agent");
      String line;
      for( int i = 0; i < 11; i++)
        rd.readLine();
      while( (line = rd.readLine()) != null )
      System.out.println( line );
      rd.close();
      con.disconnect();
      System .out.println (s);
      }

      catch (Exception e)      {e.printStackTrace();}

}

The value of string s being printed in the last line is Java/1.4.2_02, and not the one set on line 3 i the first method. Is it like this or am I doing something wrong?

0
objectsCommented:
Looks like Suns http code is setting User-Agent which would explain your problem using it.
0
Venci75Commented:
I haven't tested this, but Sun's http client should set the User-Agent header only if it is not already set.
You can use Ethereal (www.ethereal.com) to verify what exactly your client sends.
0
objectsCommented:
> but Sun's http client should set the User-Agent header only if it is not already set.

Thats what I also thought.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
format77Author Commented:
Okay so we are finally seeing the problem

The purpose of this code was to change User-Agent value dynamically as token id changes. So the server can somehow identify the program and relate it to a user using the same token id. So what i am concluding here is that once the value is set it cannot be changed? Can you please provide some specification that will act as a proof for this fact. I will also test it in the mean time, looks like the JVM is setting its own User-Agent header. And in any request after that the User-Agent header will not change.
0
sompol_kiatkamolchaiCommented:
"Java/1.4.2_02"
I think this is an agent on server side that response for your http request.
0
format77Author Commented:
Though the actual problem is not solved
But your comments helped in redesign
0
VenabiliCommented:
format77,

If you think that the question is not answered and the experts had not helped, you may request a delete? Or we can have it open for a while and I can try to find you some additional help

Venabili
0
format77Author Commented:
No Venabili its okay, with the information and limitations I provided I suppose this was the best output
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.