Write/Read cookies using HTTP and Read a file from the internet

1. Write/Read cookies using HTTP

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

class CookiesInJava {
 static Hashtable theCookies = new Hashtable();
 /**
  * Send the Hashtable (theCookies) as cookies, and write them to
  *  the specified URLconnection
  *
  * @param   urlConn  The connection to write the cookies to.
  * @param   printCookies  Print or not the action taken.
  *
  * @return  The urlConn with the all the cookies in it.
 */
 public URLConnection writeCookies
     (URLConnection urlConn, boolean printCookies){
   String cookieString = "";
   Enumeration keys = theCookies.keys();
   while (keys.hasMoreElements()) {
     String key = (String)keys.nextElement();
     cookieString += key + "=" + theCookies.get(key);
     if (keys.hasMoreElements())
        cookieString += "; ";
     }
   urlConn.setRequestProperty("Cookie", cookieString);
   if (printCookies)
      System.out.println("Wrote cookies:\n   " + cookieString);
   return urlConn;
   }

 /**
  * Read cookies from a specified URLConnection, and insert them
  *   to the Hashtable
  *  The hashtable represents the Cookies.
  *
  * @param   urlConn  the connection to read from
  * @param   printCookies  Print the cookies or not, for debugging
  * @param   reset  Clean the Hashtable or not
 */
 public void readCookies(URLConnection urlConn, boolean printCookies,
                     boolean reset){
   if (reset)
      theCookies.clear();
   int i=1;
   String hdrKey;
   String hdrString;
   String aCookie;
   while ((hdrKey = urlConn.getHeaderFieldKey(i)) != null) {
     if (hdrKey.equals("Set-Cookie")) {
        hdrString = urlConn.getHeaderField(i);
        StringTokenizer st = new StringTokenizer(hdrString,",");
        while (st.hasMoreTokens()) {
          String s = st.nextToken();
          aCookie = s.substring(0, s.indexOf(";"));
          // aCookie = hdrString.substring(0, s.indexOf(";"));
          int j = aCookie.indexOf("=");
          if (j != -1) {
             if (!theCookies.containsKey(aCookie.substring(0, j))){
               // if the Cookie do not already exist then when keep it,
               // you may want to add some logic to update 
               // the stored Cookie instead. thanks to rwhelan
               theCookies.put
                   (aCookie.substring(0, j),aCookie.substring(j + 1));
               if (printCookies){
                  System.out.println("Reading Key: " 
                     + aCookie.substring(0, j));
                  System.out.println("        Val: " 
                     + aCookie.substring(j + 1));
                  }
               }
             }
          }
      }
      i++;
     }
  }

 /**
  * Display all the cookies currently in the HashTable
  *
 */
 public void viewAllCookies() {
   System.out.println("All Cookies are:");
   Enumeration keys = theCookies.keys();
   String key;
   while (keys.hasMoreElements()){
     key = (String)keys.nextElement();
     System.out.println("   " + key + "=" +
     theCookies.get(key));
     }
   }

 /**
  * Display the current cookies in the URLConnection,
  *    searching for the: "Cookie" header
  *
  * This is Valid only after a writeCookies operation.
  *
  * @param   urlConn  The URL to print the associates cookies in.
 */
 public void viewURLCookies(URLConnection urlConn) {
   System.out.print("Cookies in this URLConnection are:\n   ");
   System.out.println(urlConn.getRequestProperty("Cookie"));
   }

 /**
  * Add a specific cookie, by hand, to the HastTable of the Cookies
  *
  * @param   _key  The Key/Name of the Cookie
  * @param   _val  The Calue of the Cookie
  * @param   printCookies  Print or not the result
 */
 public void addCookie(String _key, String _val, boolean printCookies){
   if (!theCookies.containsKey(_key)){
      theCookies.put(_key,_val);
      if (printCookies){
         System.out.println("Adding Cookie: ");
         System.out.println("   " + _key + " = " + _val);
         }
      }
   }
}

2. Read a file from the internet

import java.io.IOException;
import java.net.URL;
import java.util.Scanner;

public class NetUtils {

  private NetUtils() {}

  public static String getTextContent(URL url) throws IOException {
      Scanner s = new Scanner(url.openStream()).useDelimiter("\\Z");;
      String content = s.next();
      return content;
  }

  public static void main(String[] args) throws IOException {
    URL url = new URL("http://www.maixuanviet.com/varia/copyrightnotice.txt");
    System.out.println(NetUtils.getTextContent(url));
  }
}

3. Read a GIF or CLASS from an URL save it locally

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

 public class SuckURL {
   String aFile;
   String aURL;

   public static void main(String args[]) {
     // GIF  JAVA How-to  at Real's Home
     String url = 
       "http://www.maixuanviet.com/images/";
     SuckURL b = new SuckURL(url, "jht.gif");
     b.doit();
   }

   SuckURL(String u, String s){ 
     aURL  = u;
     aFile = s;
   }

   public void doit() {
     DataInputStream di = null;
     FileOutputStream fo = null;
     byte [] b = new byte[1];  
       
     try {
       System.out.println("Sucking " + aFile);
       System.out.println("   at " + aURL );
       // input 
       URL url = new URL(aURL + aFile);
       URLConnection urlConnection = url.openConnection();
       urlConnection.connect();
       di = new DataInputStream(urlConnection.getInputStream());

       // output
       fo = new FileOutputStream(aFile);

       //  copy the actual file
       //   (it would better to use a buffer bigger than this)
       while(-1 != di.read(b,0,1)) 
         fo.write(b,0,1);
         di.close();  
         fo.close();                
     }
     catch (Exception ex) { 
       System.out.println("Oups!!!");
       ex.printStackTrace(); 
       System.exit(1);
     }
     System.out.println("done.");  
   }
}

This example dumps a page using the HTTPS protocol:

import java.io.*;
import java.net.*;
public class URLReader {
  public static void main(String[] args) throws Exception {
    // no longer necessary since JSSE is now included in
    // recent jdk release...
    // Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    // System.setProperty("java.protocol.handler.pkgs",
    //     "com.sun.net.ssl.internal.www.protocol");  
  
    URL url = new URL("https://www.maixuanviet.com");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();

    BufferedReader in = new BufferedReader(
                new InputStreamReader(
                con.getInputStream()));
    String inputLine;

    while ((inputLine = in.readLine()) != null)
        System.out.println(inputLine);
    in.close();
    }
}

There is an issue with the root certificate from Verisign (jdk142 or less, you have an exception talking about “untrusted server”), you may want to review this note: http://sunsolve.sun.com/search/document.do?assetkey=1-26-57436-1.

Done! Happy Coding!

Related posts:

Hướng dẫn Java Design Pattern – Proxy
Spring Boot - Unit Test Cases
Adding a Newline Character to a String in Java
Java Program to Generate Date Between Given Range
Spring REST API + OAuth2 + Angular
Giới thiệu JDBC Connection Pool
Java Program to Apply DFS to Perform the Topological Sorting of a Directed Acyclic Graph
Java Program to Implement First Fit Decreasing for 1-D Objects and M Bins
Base64 encoding và decoding trong Java 8
Java – Reader to Byte Array
Java Program to find the peak element of an array using Binary Search approach
Java Program to Generate Random Hexadecimal Byte
Java Program to Generate Randomized Sequence of Given Range of Numbers
Spring Data – CrudRepository save() Method
So sánh HashSet, LinkedHashSet và TreeSet trong Java
Custom Error Pages with Spring MVC
Java Program to Check if an UnDirected Graph is a Tree or Not Using DFS
Giới thiệu luồng vào ra (I/O) trong Java
Java Program to Implement Ternary Search Tree
Lớp TreeMap trong Java
Java Program to Implement Pairing Heap
Java Program to Implement Efficient O(log n) Fibonacci generator
Java Program to Generate All Possible Subsets with Exactly k Elements in Each Subset
DynamoDB in a Spring Boot Application Using Spring Data
A Guide to the ResourceBundle
Allow user:password in URL
Spring Data JPA and Null Parameters
Serve Static Resources with Spring
Functional Interface trong Java 8
Java Program to Check if a Given Binary Tree is an AVL Tree or Not
Sending Emails with Java
An Intro to Spring Cloud Security