簡體   English   中英

如何獲取JSESSIONID cookie

[英]how to obtain a JSESSIONID cookie

我有一個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。 我明白,我需要提供一個cookie一樣解釋在這里 ,但我如何得到jSessionId在第一時間?

謝謝!

好的,這就是我的做法。 不知道有沒有更簡單的方法:

    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;
            }
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM