如何获取JSESSIONID cookie

时间:2014-04-12 15:03:08

标签: java android tomcat cookies

我有一个Android客户端,这就是我对tomcat服务器的请求:

protected String executeRequest(String url)
{
    BasicHttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 10000);

    String output = "", line = "";

    try
    {
        HttpGet getRequest = null;
        DefaultHttpClient httpClient = new DefaultHttpClient();
        try
        {
            getRequest = new HttpGet(url);
        }
        catch(Exception e)
        {
            e.printStackTrace();
            return null;
        }
        getRequest.addHeader("accept", "application/json");

        HttpResponse response = httpClient.execute(getRequest);

        if (response.getStatusLine().getStatusCode() != 200) 
        {
            response.getStatusLine().getStatusCode();
            return null;
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        while ((line = br.readLine()) != null)
        {
            output += line;
        }

        httpClient.getConnectionManager().shutdown();
    } 
    catch (ClientProtocolException e)
    {
        e.printStackTrace();
        Log.w(TAG, e.getMessage());
    } 
    catch (IllegalStateException e)
    {
        e.printStackTrace();
        Log.w(TAG, e.getMessage());
    } 
    catch (IOException e)
    {
        e.printStackTrace();
        Log.w(TAG, e.getMessage());
    }

    if(output.equals(""))
    {
        output = null;
    }

    return output;
}

现在我希望能够获得JSESSIONID cookie。我知道我需要提供类似于解释here的Cookie,但我如何在第一时间获得jSessionId

谢谢!

1 个答案:

答案 0 :(得分:0)

好的,我就是这样做的。不知道是否有更简单的方法:

    HttpResponse response = httpClient.execute(getRequest);
    Header[] headers = response.getHeaders("Set-Cookie");
    for(int i = 0; i < headers.length; i++)
    {
        if(headers[i].getName().equals("Set-Cookie"))
        {
            String pattern1 = "JSESSIONID=";
            String pattern2 = ";";
            Pattern p = Pattern.compile(Pattern.quote(pattern1) + "(.*?)" + Pattern.quote(pattern2));
            Matcher m = p.matcher(headers[i].getValue());
            if(m.find())
            {
                sessionId = m.group(1);
                break;
            }
        }
    }