HttpURLConnection

Get the date of a url connection

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

public class Main{
  public static void main(String args[]) throws Exception {
    URL url = new URL("http://www.google.com");
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();

    long date = httpCon.getDate();
    if (date == 0)
      System.out.println("No date information.");
    else
      System.out.println("Date: " + new Date(date));

 }
}

Get the document expiration date

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

public class Main{
  public static void main(String args[]) throws Exception {
    URL url = new URL("http://www.google.com");
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();

    long date = httpCon.getExpiration();
    if (date == 0)
      System.out.println("No expiration information.");
    else
      System.out.println("Expires: " + new Date(date));

 }
}

Get the document Last-modified date

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

public class Main{
  public static void main(String args[]) throws Exception {
    URL url = new URL("http://www.google.com");
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();

    long date = httpCon.getLastModified();
    if (date == 0)
      System.out.println("No last-modified information.");
    else
      System.out.println("Last-Modified: " + new Date(date));

 }
}

Show the content type

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

public class Main{
  public static void main(String args[]) throws Exception {
    URL url = new URL("http://www.google.com");
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();


    System.out.println("Content-Type: " + httpCon.getContentType());

 }
}

Show the content length

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

public class Main{
  public static void main(String args[]) throws Exception {
    URL url = new URL("http://www.google.com");
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();


    int len = httpCon.getContentLength();
    if (len == -1)
      System.out.println("Content length unavailable.");
    else
      System.out.println("Content-Length: " + len);
 }
}

Display request method

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

public class Main{
  public static void main(String args[]) throws Exception {
    URL url = new URL("http://www.google.com");
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();

    System.out.println("Request method is " + httpCon.getRequestMethod());

 }
}

Get response code

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

public class Main{
  public static void main(String args[]) throws Exception {
    URL url = new URL("http://www.google.com");
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();


    System.out.println("Response code is " + httpCon.getResponseCode());
 }
}

Display response message

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

public class Main{
  public static void main(String args[]) throws Exception {
    URL url = new URL("http://www.google.com");
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();

    System.out.println("Response Message is " + httpCon.getResponseMessage());

 }
}

Display header information

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Main{
  public static void main(String args[]) throws Exception {
    URL url = new URL("http://www.google.com");
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();

    Map<String, List<String>> hdrs = httpCon.getHeaderFields();
    Set<String> hdrKeys = hdrs.keySet();

    for (String k : hdrKeys)
      System.out.println("Key: " + k + "  Value: " + hdrs.get(k));

 }
}

Download and display the content

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
  public static void main(String args[]) throws Exception {
    URL url = new URL("http://www.google.com");
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();

    InputStream inStrm = httpCon.getInputStream();
    System.out.println("\nContent at " + url);
    int ch;
    while (((ch = inStrm.read()) != -1))
      System.out.print((char) ch);
    inStrm.close();
  }
}

A Web Page Source Viewer

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class Main extends JFrame {
  JButton go = new JButton("Get Source");

  JTextArea codeArea = new JTextArea();

  public Main() {
    JPanel inputPanel = new JPanel(new BorderLayout(3, 3));
    go.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        try {
          URL pageURL = new URL("http://www.google.com");
          HttpURLConnection urlConnection = (HttpURLConnection) pageURL.openConnection();
          int respCode = urlConnection.getResponseCode();
          String response = urlConnection.getResponseMessage();
          codeArea.setText("HTTP/1.x " + respCode + " " + response + "\n");
          int count = 1;
          while (true) {
            String header = urlConnection.getHeaderField(count);
            String key = urlConnection.getHeaderFieldKey(count);
            if (header == null || key == null) {
              break;
            }
            codeArea.append(urlConnection.getHeaderFieldKey(count) + ": " + header + "\n");
            count++;
          }
          InputStream in = new BufferedInputStream(urlConnection.getInputStream());
          Reader r = new InputStreamReader(in);
          int c;
          while ((c = r.read()) != -1) {
            codeArea.append(String.valueOf((char) c));
          }
          codeArea.setCaretPosition(1);
        } catch (Exception ee) {
        }
      }
    });
    inputPanel.add(BorderLayout.EAST, go);
    JScrollPane codeScroller = new JScrollPane(codeArea);
    add(BorderLayout.NORTH, inputPanel);
    add(BorderLayout.CENTER, codeScroller);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setSize(700, 500);
    this.setVisible(true);
  }

  public static void main(String[] args) {
    JFrame webPageSourceViewer = new Main();
  }
}

Reading from a URLConnection

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class Main {
  public static void main(String[] args) throws Exception {
    URL yahoo = new URL("http://www.yahoo.com/");
    URLConnection yc = yahoo.openConnection();
    BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
    String inputLine;

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

Use BufferedReader to read content from a URL

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class Main {
  public static void main(String[] argv) throws Exception {
    URL url = new URL("http://www.java.com");
    URLConnection urlConnection = url.openConnection();
    HttpURLConnection connection = null;
    if (urlConnection instanceof HttpURLConnection) {
      connection = (HttpURLConnection) urlConnection;
    } else {
      System.out.println("Please enter an HTTP URL.");
      return;
    }
    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String urlString = "";
    String current;
    while ((current = in.readLine()) != null) {
      urlString += current;
    }
    System.out.println(urlString);
  }
}

Check if a page exists

import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
  public static void main(String[] argv) throws Exception {
    HttpURLConnection.setFollowRedirects(false);
    HttpURLConnection con = (HttpURLConnection) new URL("http://www.google.coom").openConnection();
    con.setRequestMethod("HEAD");
    System.out.println(con.getResponseCode() == HttpURLConnection.HTTP_OK);
  }
}

Identify ourself to a proxy

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;

import sun.misc.BASE64Encoder;

public class Main {
  public static void main(String[] argv) throws Exception {
    Properties systemSettings = System.getProperties();
    systemSettings.put("proxySet", "true");
    systemSettings.put("http.proxyHost", "proxy.mycompany.local");
    systemSettings.put("http.proxyPort", "80");

    URL u = new URL("http://www.google.com");
    HttpURLConnection con = (HttpURLConnection) u.openConnection();
    BASE64Encoder encoder = new BASE64Encoder();
    String encodedUserPwd = encoder.encode("domain\\username:password".getBytes());
    con.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPwd);
    con.setRequestMethod("HEAD");
    System.out.println(con.getResponseCode() + " : " + con.getResponseMessage());
    System.out.println(con.getResponseCode() == HttpURLConnection.HTTP_OK);
  }
}

Connect through a Proxy

import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;

import sun.misc.BASE64Encoder;

public class Main {
  public static void main(String[] argv) throws Exception {
    byte[] b = new byte[1];
    Properties systemSettings = System.getProperties();
    systemSettings.put("http.proxyHost", "proxy.mydomain.local");
    systemSettings.put("http.proxyPort", "80");

    URL u = new URL("http://www.google.com");
    HttpURLConnection con = (HttpURLConnection) u.openConnection();
    BASE64Encoder encoder = new BASE64Encoder();
    String encodedUserPwd = encoder.encode("mydomain\\MYUSER:MYPASSWORD".getBytes());
    con.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPwd);
    DataInputStream di = new DataInputStream(con.getInputStream());
    while (-1 != di.read(b, 0, 1)) {
      System.out.print(new String(b));
    }
  }
}

java.net.Authenticator can be used to send the credentials when needed

import java.io.DataInputStream;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.util.Properties;

public class Main {
  public static void main(String[] argv) throws Exception {
    byte[] b = new byte[1];
    Properties systemSettings = System.getProperties();
    systemSettings.put("http.proxyHost", "proxy.mydomain.local");
    systemSettings.put("http.proxyPort", "80");

    Authenticator.setDefault(new Authenticator() {
      protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("mydomain\\username", "password".toCharArray());
      }
    });

    URL u = new URL("http://www.google.com");
    HttpURLConnection con = (HttpURLConnection) u.openConnection();
    DataInputStream di = new DataInputStream(con.getInputStream());
    while (-1 != di.read(b, 0, 1)) {
      System.out.print(new String(b));
    }
  }
}

Read data from a URL

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class WebReader extends JFrame {
  JTextArea box = new JTextArea("Getting data ...");

  public WebReader() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(600, 300);
    JScrollPane pane = new JScrollPane(box);
    add(pane);
    setVisible(true);
  }

  void getData(String address) throws Exception {
    setTitle(address);
    URL page = new URL(address);
    StringBuffer text = new StringBuffer();
    HttpURLConnection conn = (HttpURLConnection) page.openConnection();
    conn.connect();
    InputStreamReader in = new InputStreamReader((InputStream) conn.getContent());
    BufferedReader buff = new BufferedReader(in);
    box.setText("Getting data ...");
    String line;
    do {
      line = buff.readLine();
      text.append(line + "\n");
    } while (line != null);
    box.setText(text.toString());
  }

  public static void main(String[] arguments) throws Exception {
    WebReader app = new WebReader();
    app.getData("http://java2s.com");
  }
}

Dump a page using the HTTPS protocol

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
  public static void main(String[] argv) throws Exception {

    URL url = new URL("https://www.server.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();
  }
}

Save URL contents to a file

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.lang.reflect.Member;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;


import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

/**
 * Contains various unorganized static utility methods used across Cayenne.
 * 
 * @author Andrei Adamchik
 */
public class Util {

  /**
   * Copies file contents from source to destination. Makes up for the lack of file
   * copying utilities in Java
   */
  public static boolean copy(File source, File destination) {
      BufferedInputStream fin = null;
      BufferedOutputStream fout = null;
      try {
          int bufSize = 8 * 1024;
          fin = new BufferedInputStream(new FileInputStream(source), bufSize);
          fout = new BufferedOutputStream(new FileOutputStream(destination), bufSize);
          copyPipe(fin, fout, bufSize);
      }
      catch (IOException ioex) {
          return false;
      }
      catch (SecurityException sx) {
          return false;
      }
      finally {
          if (fin != null) {
              try {
                  fin.close();
              }
              catch (IOException cioex) {
              }
          }
          if (fout != null) {
              try {
                  fout.close();
              }
              catch (IOException cioex) {
              }
          }
      }
      return true;
  }

  /**
   * Save URL contents to a file.
   */
  public static boolean copy(URL from, File to) {
      BufferedInputStream urlin = null;
      BufferedOutputStream fout = null;
      try {
          int bufSize = 8 * 1024;
          urlin = new BufferedInputStream(
                  from.openConnection().getInputStream(),
                  bufSize);
          fout = new BufferedOutputStream(new FileOutputStream(to), bufSize);
          copyPipe(urlin, fout, bufSize);
      }
      catch (IOException ioex) {
          return false;
      }
      catch (SecurityException sx) {
          return false;
      }
      finally {
          if (urlin != null) {
              try {
                  urlin.close();
              }
              catch (IOException cioex) {
              }
          }
          if (fout != null) {
              try {
                  fout.close();
              }
              catch (IOException cioex) {
              }
          }
      }
      return true;
  }

  /**
   * Reads data from the input and writes it to the output, until the end of the input
   * stream.
   * 
   * @param in
   * @param out
   * @param bufSizeHint
   * @throws IOException
   */
  public static void copyPipe(InputStream in, OutputStream out, int bufSizeHint)
          throws IOException {
      int read = -1;
      byte[] buf = new byte[bufSizeHint];
      while ((read = in.read(buf, 0, bufSizeHint)) >= 0) {
          out.write(buf, 0, read);
      }
      out.flush();
  }

}












































































發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章