Solved

Java Http Client, passing it session id

Posted on 2004-08-10
21
3,757 Views
Last Modified: 2012-06-21
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;
}

0
Comment
Question by:format77
  • 7
  • 4
  • 3
  • +3
21 Comments
 
LVL 11

Expert Comment

by:sompol_kiatkamolchai
ID: 11768965
>>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
 

Author Comment

by:format77
ID: 11769011
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
 
LVL 92

Expert Comment

by:objects
ID: 11769206
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
 

Author Comment

by:format77
ID: 11769230
Hi

I am using 1.4.2

0
 
LVL 92

Expert Comment

by:objects
ID: 11769250
maybe worth trying 1.5 to see if Sun have made any improvements.
0
 
LVL 11

Expert Comment

by:sompol_kiatkamolchai
ID: 11769296
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
 
LVL 35

Expert Comment

by:girionis
ID: 11770054
Can you not pass the session id through a post method?
0
 
LVL 9

Expert Comment

by:Venci75
ID: 11770238
try to replace line 3 with this one:
con.setRequestProperty("Cookie",headerData); //line 3
0
 

Author Comment

by:format77
ID: 11772557
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
 
LVL 35

Expert Comment

by:girionis
ID: 11772636
>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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 9

Expert Comment

by:Venci75
ID: 11772743
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
 

Author Comment

by:format77
ID: 11774608
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
 
LVL 92

Expert Comment

by:objects
ID: 11779837
Looks like Suns http code is setting User-Agent which would explain your problem using it.
0
 
LVL 9

Assisted Solution

by:Venci75
Venci75 earned 150 total points
ID: 11781050
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
 
LVL 92

Accepted Solution

by:
objects earned 150 total points
ID: 11782000
> but Sun's http client should set the User-Agent header only if it is not already set.

Thats what I also thought.
0
 

Author Comment

by:format77
ID: 11783595
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
 
LVL 11

Assisted Solution

by:sompol_kiatkamolchai
sompol_kiatkamolchai earned 200 total points
ID: 11790061
"Java/1.4.2_02"
I think this is an agent on server side that response for your http request.
0
 

Author Comment

by:format77
ID: 11851509
Though the actual problem is not solved
But your comments helped in redesign
0
 
LVL 20

Expert Comment

by:Venabili
ID: 11851799
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
 

Author Comment

by:format77
ID: 11856154
No Venabili its okay, with the information and limitations I provided I suppose this was the best output
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This video teaches viewers about errors in exception handling.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now