如何维护与Jersey客户端的会话?

时间:2015-01-20 16:27:39

标签: java session jax-rs jersey-2.0 jersey-client

我需要为客户端应用程序进行双向身份验证,为此我需要维护相同的会话。由于来自同一客户端的第二个请求应与第一个请求不同。但服务器将这两个请求视为第一个。我应该如何维持会话,以便必须区别对待第二个请求?

任何人都可以帮助我。

感谢。

以下是我的代码。

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<String,Object> 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)) > 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);
    }

}

1 个答案:

答案 0 :(得分:0)

您正在为每次通话构建新客户端。 这条线应该在外面:

client = ClientBuilder.newBuilder().sslContext(sslContext).hostnameVerifier(hv).build();

另外,如果你使用Java EE并且外部类是bean,你应该考虑它的范围(应该有状态)。