簡體   English   中英

如何設置java.net.URLConnection對象以確保后續對同一URL的調用不會共享會話數據?

[英]how to dispose a java.net.URLConnection object in order to ensure that subsequent calls to the same URL don't share session data?

我在連續多次調用相同的https URL時遇到問題。 最初的請求成功,但是經過一段不確定的時間后,拋出401 HTTP錯誤代碼異常,表明用戶憑據無效。

我與數據庫/服務器負責人討論了這個問題,他告訴我我遇到的問題是正常的,因為經過一段固定的時間后,服務器使會話數據無效,從而導致隨后使用相同的URL調用相同的URL用戶憑據以生成401 HTTP錯誤代碼。

他指出,如果我讓不同的URLConnection對象處理所有需要進行的調用,那么我不必擔心會話數據過期。

他的解釋似乎是有道理的,但是正如下面的代碼片段所示,我已經在使用相同用戶憑證的相同URL的每個請求中使用了全新的URLConnection對象。 因此,如果我被告知是正確的,那么我想問題是URLConnection對象都使用相同的基礎連接,因此共享相同的會話數據。

假設我走了正確的路,應該如何修改代碼,以便每次使用相同的用戶憑據向相同的URL發出新請求時,我都不會遇到會話數據過期引起的問題? 僅僅是在基礎HttpsURLConnection對象上調用disconnect()的問題嗎?

public static void main(String[] args)
{
    String url = "https://...";//some https url
    int x = 0;
    while(true)
    {
        try
        {
            System.out.print("call#: " + (++x));

            //call download() with a valid username & password
            String result = download(url, "some-valid-username", "some-valid-password");
            System.out.println(result);
        }
        catch(Throwable e)
        {
            //after hundreds of successful calls,
            //a 401 HTTP error code exception
            e.printStackTrace();
            break;
        }
    }
}

public static String download(String url, String user, String pass) throws IOException
{
    //new URLConnection object
    java.net.URLConnection connection = new java.net.URL(url).openConnection();
    connection.setRequestProperty("Authorization",
            "Basic " +
                javax.xml.bind.DatatypeConverter.printBase64Binary(
                        (user + ":" + pass).getBytes("UTF-8")));

    //get response
    InputStream is = null;
    byte[] response = null;
    try
    {
        is = connection.getInputStream();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        byte[] bytes = new byte[16384];
        int x = 0;
        while((x = is.read(bytes, 0, bytes.length)) != -1){
            stream.write(bytes, 0, x);
        }
        stream.flush();
        response = stream.toByteArray();
    }
    finally
    {
        if (is != null)
        {
            is.close();
        }
    }
    //((javax.net.ssl.HttpsURLConnection)connection).disconnect();// ?

    return response != null ? new String(response, "UTF-8") : null;
}

服務器將根據您的登錄憑據創建會話ID,並由服務器維護。 您的后續通話將根據會話ID而不是您的憑據進行驗證。 您需要在第一時間獲取會話ID並在您的應用程序中進行維護。 將其傳遞給服務器以進行后續調用。 如果沒有任何請求發送到服務器,則該會話將在特定的預定時間段后過期。

請閱讀

http://en.wikipedia.org/wiki/Session_%28computer_science%29

暫無
暫無

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

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