Java by API/java.net/URLConnection — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Текущая версия на 14:17, 31 мая 2010

URLConnection: connect() throws IOException

  
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class Main {
  public static void main(String[] argv) throws Exception {
    
    URLConnection conn = new URL("http://www.yourserver.ru").openConnection();
    conn.setDoInput(true);
    conn.setRequestProperty("Authorization", "asdfasdf");
    conn.connect();
    InputStream in = conn.getInputStream();
  }
}





URLConnection: getContentEncoding()

 
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class MainClass {
  public static void main(String args[]) {
    try {
      URL u = new URL("http://www.jexp.ru");
      URLConnection uc = u.openConnection();
      System.out.println("Content-encoding: " + uc.getContentEncoding());
    } catch (MalformedURLException e) {
      System.err.println("not a URL I understand");
    } catch (IOException e) {
      System.err.println(e);
    }
  }
}





URLConnection: getContentType()

  
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.StringTokenizer;
public class Main {
  public static void main(String args[]) throws Exception {
    int c;
    URL hp = new URL("http://www.internic.net");
    URLConnection hpCon = hp.openConnection();
    long d = hpCon.getDate();
    if (d == 0)
      System.out.println("No date information.");
    else
      System.out.println("Date: " + new Date(d));
    System.out.println("Content-Type: " + hpCon.getContentType());
    d = hpCon.getExpiration();
    if (d == 0)
      System.out.println("No expiration information.");
    else
      System.out.println("Expires: " + new Date(d));
    d = hpCon.getLastModified();
    if (d == 0)
      System.out.println("No last-modified information.");
    else
      System.out.println("Last-Modified: " + new Date(d));
    int len = hpCon.getContentLength();
    if (len == -1)
      System.out.println("Content length unavailable.");
    else
      System.out.println("Content-Length: " + len);
    if (len != 0) {
      InputStream input = hpCon.getInputStream();
      int i = len;
      while (((c = input.read()) != -1)) { // && (--i > 0)) {
        System.out.print((char) c);
      }
      input.close();
    } else {
      System.out.println("No content available.");
    }
  }
}





URLConnection: getExpiration()

  
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.StringTokenizer;
public class Main {
  public static void main(String args[]) throws Exception {
    int c;
    URL hp = new URL("http://www.internic.net");
    URLConnection hpCon = hp.openConnection();
    long d = hpCon.getDate();
    if (d == 0)
      System.out.println("No date information.");
    else
      System.out.println("Date: " + new Date(d));
    System.out.println("Content-Type: " + hpCon.getContentType());
    d = hpCon.getExpiration();
    if (d == 0)
      System.out.println("No expiration information.");
    else
      System.out.println("Expires: " + new Date(d));
    d = hpCon.getLastModified();
    if (d == 0)
      System.out.println("No last-modified information.");
    else
      System.out.println("Last-Modified: " + new Date(d));
    int len = hpCon.getContentLength();
    if (len == -1)
      System.out.println("Content length unavailable.");
    else
      System.out.println("Content-Length: " + len);
    if (len != 0) {
      InputStream input = hpCon.getInputStream();
      int i = len;
      while (((c = input.read()) != -1)) { // && (--i > 0)) {
        System.out.print((char) c);
      }
      input.close();
    } else {
      System.out.println("No content available.");
    }
  }
}





URLConnection: getHeaderField(int n)

 
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class MainClass {
  public static void main(String args[]) {
    URL u;
    URLConnection uc;
    String header;
    try {
      u = new URL("http://www.jexp.ru");
      uc = u.openConnection();
      for (int j = 1;; j++) {
        header = uc.getHeaderField(j);
        if (header == null)
          break;
        System.out.println(uc.getHeaderFieldKey(j) + " " + header);
      }
    } catch (MalformedURLException e) {
      System.err.println("not a URL I understand.");
    } catch (IOException e) {
      System.err.println(e);
    }
  }
}





URLConnection: getHeaderFieldKey(int n)

 
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class MainClass {
  public static void main(String args[]) {
    URL u;
    URLConnection uc;
    String header;
    try {
      u = new URL("http://www.jexp.ru");
      uc = u.openConnection();
      for (int j = 1;; j++) {
        header = uc.getHeaderField(j);
        if (header == null)
          break;
        System.out.println(uc.getHeaderFieldKey(j) + " " + header);
      }
    } catch (MalformedURLException e) {
      System.err.println("not a URL I understand.");
    } catch (IOException e) {
      System.err.println(e);
    }
  }
}





URLConnection: getHeaderFields()

  
 
 import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
public class Main {
  public static void main(String[] args) throws Exception {
    String s;
    s = "http://www.y.ru/authTest";
    URL url = new URL(s);
    URLConnection urlc = url.openConnection();
    Map<String, List<String>> hf = urlc.getHeaderFields();
    for (String key : hf.keySet())
      System.out.println(key + ": " + urlc.getHeaderField(key));
    System.out.println(((HttpURLConnection) urlc).getResponseCode());
  }
}





URLConnection: getIfModifiedSince()

 
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
public class MainClass {
  public static void main(String[] args) {
    try {
      URLConnection uc = new URL("http://www.demo2s.ru").openConnection();
      System.out.println("Will retrieve file if it"s been modified since "
          + new Date(uc.getIfModifiedSince()));
      uc.setIfModifiedSince(System.currentTimeMillis());
      System.out.println("Will retrieve file if it"s been modified since "
          + new Date(uc.getIfModifiedSince()));
    } catch (Exception e) {
      System.err.println(e);
    }
  }
}





URLConnection: getInputStream()

  
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.StringTokenizer;
public class Main {
  public static void main(String args[]) throws Exception {
    int c;
    URL hp = new URL("http://www.internic.net");
    URLConnection hpCon = hp.openConnection();
    long d = hpCon.getDate();
    if (d == 0)
      System.out.println("No date information.");
    else
      System.out.println("Date: " + new Date(d));
    System.out.println("Content-Type: " + hpCon.getContentType());
    d = hpCon.getExpiration();
    if (d == 0)
      System.out.println("No expiration information.");
    else
      System.out.println("Expires: " + new Date(d));
    d = hpCon.getLastModified();
    if (d == 0)
      System.out.println("No last-modified information.");
    else
      System.out.println("Last-Modified: " + new Date(d));
    int len = hpCon.getContentLength();
    if (len == -1)
      System.out.println("Content length unavailable.");
    else
      System.out.println("Content-Length: " + len);
    if (len != 0) {
      InputStream input = hpCon.getInputStream();
      int i = len;
      while (((c = input.read()) != -1)) { // && (--i > 0)) {
        System.out.print((char) c);
      }
      input.close();
    } else {
      System.out.println("No content available.");
    }
  }
}





URLConnection: getLastModified()

  
import java.net.URL;
import java.net.URLConnection;
public class Main {
  public static void main(String[] argv) throws Exception {
    URL u = new URL("http://127.0.0.1/test.gif");
    URLConnection uc = u.openConnection();
    uc.setUseCaches(false);
    long timestamp = uc.getLastModified();
  }
}





URLConnection: getURL()

 
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class MainClass {
  public static void main(String args[]) {
    URL u;
    URLConnection uc;
    try {
      u = new URL("http://www.jexp.ru/");
      try {
        uc = u.openConnection();
        System.out.println(uc.getURL());
      } catch (IOException e) {
        System.err.println(e);
      }
    } catch (MalformedURLException e) {
      System.err.println(e);
    }
  }
}





URLConnection: setAllowUserInteraction(boolean allowuserinteraction)

 
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class MainClass {
  public static void main(String[] args) {
    try {
      MyHttpHandler handler = new MyHttpHandler();
      URLConnection uc = handler.openConnection(new URL("http://www.ora.ru"));
      if (!uc.getAllowUserInteraction()) {
        uc.setAllowUserInteraction(true);
      }
    } catch (MalformedURLException e) {
      System.err.println(e);
    } catch (IOException e) {
      System.err.println(e);
    }
  }
}
class MyHttpHandler extends sun.net.www.protocol.http.Handler {
  public URLConnection openConnection(URL u) throws IOException {
    return super.openConnection(u);
  }
}





URLConnection: setDoInput(boolean doinput)

 
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.URL;
import java.net.URLConnection;
public class MainClass {
  public static void main(String args[]) throws Exception {
    String query = "name=yourname&email=youremail@yourserver.ru";
    URLConnection uc = new URL("http:// your form ").openConnection();
    uc.setDoOutput(true);
    uc.setDoInput(true);
    uc.setAllowUserInteraction(false);
    DataOutputStream dos = new DataOutputStream(uc.getOutputStream());
    // The POST line, the Accept line, and
    // the content-type headers are sent by the URLConnection.
    // We just need to send the data
    dos.writeBytes(query);
    dos.close();
    // Read the response
    DataInputStream dis = new DataInputStream(uc.getInputStream());
    String nextline;
    while ((nextline = dis.readLine()) != null) {
      System.out.println(nextline);
    }
    dis.close();
  }
}





URLConnection: setDoOutput(boolean dooutput)

 
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.URL;
import java.net.URLConnection;
public class MainClass {
  public static void main(String args[]) throws Exception {
    String query = "name=yourname&email=youremail@yourserver.ru";
    URLConnection uc = new URL("http:// your form ").openConnection();
    uc.setDoOutput(true);
    uc.setDoInput(true);
    uc.setAllowUserInteraction(false);
    DataOutputStream dos = new DataOutputStream(uc.getOutputStream());
    // The POST line, the Accept line, and
    // the content-type headers are sent by the URLConnection.
    // We just need to send the data
    dos.writeBytes(query);
    dos.close();
    // Read the response
    DataInputStream dis = new DataInputStream(uc.getInputStream());
    String nextline;
    while ((nextline = dis.readLine()) != null) {
      System.out.println(nextline);
    }
    dis.close();
  }
}





URLConnection: setIfModifiedSince(long ifmodifiedsince)

 
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
public class MainClass {
  public static void main(String[] args) {
    try {
      URLConnection uc = new URL("http://www.demo2s.ru").openConnection();
      System.out.println("Will retrieve file if it"s been modified since "
          + new Date(uc.getIfModifiedSince()));
      uc.setIfModifiedSince(System.currentTimeMillis());
      System.out.println("Will retrieve file if it"s been modified since "
          + new Date(uc.getIfModifiedSince()));
    } catch (Exception e) {
      System.err.println(e);
    }
  }
}





URLConnection: setRequestProperty(String key, String value)

  
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
class MainClass {
  public static void main(String[] args) throws Exception {
    URL url = new URL("http://www.x.ru");
    URLConnection urlc = url.openConnection();
    urlc.setRequestProperty("User-Agent", "Mozilla 5.0 (Windows; U; "
        + "Windows NT 5.1; en-US; rv:1.8.0.11) ");
    InputStream is = urlc.getInputStream();
    int c;
    while ((c = is.read()) != -1)
      System.out.print((char) c);
  }
}





URLConnection: setUseCaches(boolean usecaches)

 
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class MainClass {
  public static void main(String[] args) {
    URL u;
    URLConnection uc;
    try {
      u = new URL("http://www.jexp.ru");
      try {
        uc = u.openConnection();
        if (uc.getUseCaches()) {
          uc.setUseCaches(false);
        }
      } catch (IOException e) {
        System.err.println(e);
      }
    } catch (MalformedURLException e) {
      System.err.println(e);
    }
  }
}