title: How to maintain a session with Jersey Client ?
body: <p>I need to do a two way authentication for a client side application and for that i need to maintain the same session. Since the second request from the same client should differ from first request. But the server is seeing both the requests as the first. How should i be able to maintain the session such that the second request must be treated differently ? </p>
  
  <p>Can any one help me out here.</p>
  
  <p>Thanks.</p>
  
  <p>Below is my code.</p>
  
  <pre><code>public class ESBLClient {
      private static final Logger logger = Logger.getLogger(ESBLClient.class.getName());
      static String REQUEST_SRPID = "S9000";
      static String GOOD_AUTH_KEY = "8kP4cP9CkzYUAEtTIzUPfSMdzVQ=";
      static String BAD_AUTH_KEY    = "DZe6GI4MGnTASYWPOIWERASHaseopyiqQ1akGK00ves=";
      static String REQUEST_BODY = "[{'IMEI': '49015420323751'}, {'IMSI': '2222'}, {'IMEI': '1111', 'IMSI': '321456987'}]";
  
      public void request_ssps(String uid, String authkey64, String request_body) {
                  Client client = null;
                  try {
  
              client = ClientBuilder.newBuilder().sslContext(sslContext).hostnameVerifier(hv).build();
  
              System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
              client = ClientBuilder.newClient();
              client.register(new LoggingFilter(logger, true));
              SecureRandom random = new SecureRandom();
              byte challenge[] = random.generateSeed(32);
              // Generating base64 of challenge   
              String challange64 = Base64.encode(challenge);      
              //Convert auth key to binary            
              byte[] authkey = Base64.decode(authkey64);          
              SecretKeySpec keySpec = new SecretKeySpec(authkey,"HmacSHA1"); 
              Mac mac = Mac.getInstance("HmacSHA1");
              mac.init(keySpec);          
              byte[] rawHmac = mac.doFinal(challenge); 
              BASE64Encoder encoder = new BASE64Encoder();
              String ExpectedServerResponse = encoder.encode(rawHmac);
  
              WebTarget webTarget = client
                      .target("http://10.236.65.14:8080").path("authz").path("ssp/"); 
                  Invocation.Builder invocationBuilder1 = webTarget
                      .request(MediaType.TEXT_PLAIN_TYPE)
                      .header("Accept-Encoding","gzip, deflate")
                      .header("Content-Type", "application/json-v3")
                      .header("Accept", "application/json-v3")
                      .header("Sender","ESBL 001")
                      .header("Version", "AAAWS/1.0")
                      .header("SRPID", uid)
                      .header("Connection","keep-alive")
                      .header("challenge", challange64);
  
              Response postResponse1 = invocationBuilder1.get();
              try
              {
                  // Raise an error if serverresponse and expectedserverresponse are different
                  String serverResponse = postResponse1.getHeaderString("ChallengeResponse");
                  if(!ExpectedServerResponse.equals(serverResponse))
                  {
                      System.err.println("WARNING: Server challange response doesn't match expected value");
                  }
                  String serverChallenge64 = postResponse1.getHeaderString("Challenge");  
                  //Decode the server response
                  byte[] serverChallenge= new BASE64Decoder().decodeBuffer(serverChallenge64);
                  //Calculate hmac-sha1 of server challenge using authkey and base64 encode                               
                  byte[] challengeRespBy = mac.doFinal(serverChallenge);
                  for(byte b:challengeRespBy)
                      System.out.print(b);
  
                  String challengeResponse = encoder.encode(challengeRespBy);
  
                  //Second round request
                  Invocation.Builder invocationBuilder2 = webTarget
                          .request(MediaType.TEXT_PLAIN_TYPE)
                          .header("Accept-Encoding","gzip, deflate")
                          .header("Content-Type", "application/json-v3")
                          .header("Accept", "application/json-v3")
                          .header("Sender","ESBL 001")
                          .header("Version", "AAAWS/1.0")
                          .header("SRPID", uid)
                          .header("Connection","keep-alive")
                          .header("ChallengeResponse", challengeResponse); 
                  Response postResponse2 = invocationBuilder2.post(Entity.entity(request_body,MediaType.APPLICATION_JSON));   
  
                  postResponse2.getEntity()   ;   //.readEntity();
  
                  MultivaluedMap&lt;String,Object&gt; headers = postResponse2.getHeaders(); 
                  LinkedList contentType = (LinkedList) headers.get("Content-Encoding");
                  //Response body 
                  String body =""; 
                  if(contentType.contains("gzip"))
                  {
                      BufferedInputStream bais  = null;
                      Reader reader = null;
                      StringWriter writer = null;
                      String charset = "UTF-8";
                      try {
                          bais = (BufferedInputStream) postResponse2.getEntity();
                          InputStream ungzippedResponse = new GZIPInputStream(bais);
                          reader = new InputStreamReader(ungzippedResponse, charset);
                          writer = new StringWriter();
  
                          char[] buffer = new char[10240];
                          for (int length = 0; (length = reader.read(buffer)) &gt; 0;) {
                              writer.write(buffer, 0, length);                        }
                      }
                      catch(Exception e)
                      {
                          e.printStackTrace();
                      }
                      finally {
                          writer.close();;
                          reader.close();
                      }
                      body = writer.toString();    
                  }else{
                      body = postResponse2.readEntity(String.class);
                  }   
              }
              catch(Exception e)
              {
                  e.printStackTrace();
              }
  
          } catch (Exception e) {
              e.printStackTrace();
          } finally {
              client.close();
          }
      }
  
      public static void main(String[] args)
      {
          ESBLClient a = new ESBLClient();
          a.request_ssps(REQUEST_SRPID, GOOD_AUTH_KEY, REQUEST_BODY);
      }
  
  }
  </code></pre>