Search code examples
javaurlcookiesauthenticationurlconnection

How can I login to site after URLConnection in Java?


How can I login to site after URLConnection in Java?

I'm doing URLConnection in this way:

URL url = new URL("https://www.linkedin.com/in/williamhgates");
URLConnection urlConnection = url.openConnection();
Scanner scanner = new Scanner(new InputStreamReader(urlConnection.getInputStream()));
while (scanner.hasNext())
    System.out.println(scanner.nextLine());

After connection i am receiving a welcome page, but i need "https://www.linkedin.com/in/williamhgates".

  • How can i login to my linkedin?
  • How can receive a cookie?
  • How can i send a cookie at next time? Can i send a cookie taken on my web browser?

UPD: To take a cookie i'm using:

String cookie = urlConnection.getHeaderFields().get("Set-Cookie").get(0);

Solution

  • How can I receive a cookie?

            connection.getHeaderFields();
    

    Look through the output and look for the Set-Cookie header. After that there should be GUID = .... That is your cookie.

    After you've gotten the cookie, and stored it somewhere, the easiest way to "send" the website your cookie is using this:

            connection.setRequestProperty("Cookie", cookie);
    

    cookie being a string.

    Use a HTTTP Listener addon on your browser and connect to the website that way. https://gyazo.com/789db4f2ccb90d97516663de4ad1c6fa

    With this knowledge, you can just repeat what the browser did in your app. Like:

     connection.setRequestProperty(*Request header*,*value of request header*);
    

    You can't send your browser's cookie.