簡體   English   中英

嘗試使用java.net登錄到網站,但不確定如何處理Cookie

[英]Trying to login to a website with java.net but not sure how to handle cookies

嘗試登錄時,我一直收到“您的會話超時”的消息,我懷疑它是由於根本沒有處理Cookie所致。 HTTPS會阻止我通過Java登錄嗎?

這是代碼:

package logintopage;

import java.net.*;
import java.io.*;

public class LoginToPage{

// Variables to hold the URL object and its connection to that URL.
private static URL URLObj;
private static URLConnection connect;

public static void main(String[] args) {
    try {
        // Establish a URL and open a connection to it. Set it to output mode.
        URLObj = new URL("my url");
        connect = URLObj.openConnection();
        connect.setDoOutput(true);  


    }
    catch (MalformedURLException ex) {
        System.out.println("The URL specified was unable to be parsed or uses an invalid protocol. Please try again.");
        System.exit(1); 
    }
    catch (Exception ex) {
        System.out.println("An exception occurred. " + ex.getMessage());
        System.exit(1);
    }


    try {

        // Create a buffered writer to the URLConnection's output stream and write our forms parameters.
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connect.getOutputStream()));

        writer.write("userIdentifier=user&password=pass&LoginUser=Sign+In");
        writer.close();

        // Now establish a buffered reader to read the URLConnection's input stream.
        BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));

        String lineRead = "";

        // Read all available lines of data from the URL and print them to screen.
        while ((lineRead = reader.readLine()) != null) {
            System.out.println(lineRead);
        }

        reader.close();
    }
    catch (Exception ex) {
        System.out.println("There was an error reading or writing to the URL: " + ex.getMessage());
    }
}

我對Java網絡世界還很陌生,因此非常感謝幫助和信息源。

上面的代碼僅適用於http連接。

如果需要通過https連接到URL,則需要使用SSLSocket和SSLSocketFactory類。 看一下這個基本示例: http : //www.jguru.com/faq/view.jsp? EID = 32388http://www.javacodegeeks.com/2013/06/java-security-tutorial-step逐步引導到創建-SSL的連接和- certificates.html

您可能還考慮將代碼簡化為:

URLObj =新網址(“ my_url?userIdentifier = user&password = pass&LoginUser = Sign + In”);

暫無
暫無

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

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