URLConnection的使用

An URLConnection for HTTP (RFC 2616) used to send and receive data over the web. Data may be of any type and length. This class may be used to send and receive streaming data whose length is not known in advance.

Uses of this class follow a pattern:

  1. Obtain a new HttpURLConnection by calling URL.openConnection() and casting the result to HttpURLConnection.
  2. Prepare the request. The primary property of a request is its URI. Request headers may also include metadata such as credentials, preferred content types, and session cookies.
  3. Optionally upload a request body. Instances must be configured with setDoOutput(true) if they include a request body. Transmit data by writing to the stream returned by getOutputStream().
  4. Read the response. Response headers typically include metadata such as the response body‘s content type and length, modified dates and session cookies. The response body may be read from the stream returned by getInputStream(). If the response has no body, that method returns an empty stream.
  5. Disconnect. Once the response body has been read, the HttpURLConnection should be closed by calling disconnect(). Disconnecting releases the resources held by a connection so they may be closed or reused.

For example, to retrieve the webpage at http://www.android.com/:

   URL url = new URL("http://www.android.com/");    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();    try {      InputStream in = new BufferedInputStream(urlConnection.getInputStream());      readStream(in);     finally {      urlConnection.disconnect();    }  }

Secure Communication with HTTPS

Calling 
openConnection()
 on a URL with the "https" scheme will return an HttpsURLConnection
, which allows for overriding the default
HostnameVerifier
 and 
SSLSocketFactory
. An application-supplied SSLSocketFactory
 created from an 
SSLContext
 can provide a custom 
X509TrustManager
 for verifying certificate chains and a custom 
X509KeyManager
 for supplying client certificates. See
HttpsURLConnection
 for more details.

Response Handling

HttpURLConnection
 will follow up to five HTTP redirects. It will follow redirects from one origin server to another. This implementation doesn‘t follow redirects from HTTPS to HTTP or vice versa.

If the HTTP response indicates that an error occurred, getInputStream() will throw an IOException. Use getErrorStream() to read the error response. The headers can be read in the normal way using getHeaderFields(),

Posting Content

To upload data to a web server, configure the connection for output using 
setDoOutput(true)
.

For best performance, you should call either setFixedLengthStreamingMode(int) when the body length is known in advance, orsetChunkedStreamingMode(int) when it is not. Otherwise HttpURLConnection will be forced to buffer the complete request body in memory before it is transmitted, wasting (and possibly exhausting) heap and increasing latency.

For example, to perform an upload:

   HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();    try {      urlConnection.setDoOutput(true);      urlConnection.setChunkedStreamingMode(0);      OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());      writeStream(out);      InputStream in = new BufferedInputStream(urlConnection.getInputStream());      readStream(in);     finally {      urlConnection.disconnect();    }  }

Performance

The input and output streams returned by this class are 
not buffered
. Most callers should wrap the returned streams with
BufferedInputStream
 or 
BufferedOutputStream
. Callers that do only bulk reads or writes may omit buffering.

When transferring large amounts of data to or from a server, use streams to limit how much data is in memory at once. Unless you need the entire body to be in memory at once, process it as a stream (rather than storing the complete body as a single byte array or string).

To reduce latency, this class may reuse the same underlying Socket for multiple request/response pairs. As a result, HTTP connections may be held open longer than necessary. Calls to disconnect() may return the socket to a pool of connected sockets. This behavior can be disabled by setting the http.keepAlive system property to false before issuing any HTTP requests. The http.maxConnections property may be used to control how many idle connections to each server will be held.

By default, this implementation of HttpURLConnection requests that servers use gzip compression and it automatically decompresses the data for callers of getInputStream(). The Content-Encoding and Content-Length response headers are cleared in this case. Gzip compression can be disabled by setting the acceptable encodings in the request header:

   urlConnection.setRequestProperty("Accept-Encoding", "identity");  

Setting the Accept-Encoding request header explicitly disables automatic decompression and leaves the response headers intact; callers must handle decompression as needed, according to the Content-Encoding header of the response.

getContentLength() returns the number of bytes transmitted and cannot be used to predict how many bytes can be read fromgetInputStream() for compressed streams. Instead, read that stream until it is exhausted, i.e. when read() returns -1.

Handling Network Sign-On

Some Wi-Fi networks block Internet access until the user clicks through a sign-on page. Such sign-on pages are typically presented by using HTTP redirects. You can use 
getURL()
 to test if your connection has been unexpectedly redirected. This check is not valid until 
after
 the response headers have been received, which you can trigger by calling 
getHeaderFields()
 or 
getInputStream()
. For example, to check that a response was not redirected to an unexpected host:

   HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();    try {      InputStream in = new BufferedInputStream(urlConnection.getInputStream());      if (!url.getHost().equals(urlConnection.getURL().getHost())) {        // we were redirected! Kick the user out to the browser to sign on?            ...    } finally {      urlConnection.disconnect();    }  }

HTTP Authentication

HttpURLConnection
 supports 
HTTP basic authentication
. Use 
Authenticator
 to set the VM-wide authentication handler:

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

Unless paired with HTTPS, this is 
not
 a secure mechanism for user authentication. In particular, the username, password, request and response are all transmitted over the network without encryption.

Sessions with Cookies

To establish and maintain a potentially long-lived session between client and server, HttpURLConnection
 includes an extensible cookie manager. Enable VM-wide cookie management using 
CookieHandler
 and 
CookieManager
:

   CookieManager cookieManager = new CookieManager();    CookieHandler.setDefault(cookieManager);  

By default, CookieManager
 accepts cookies from the 
origin server
 only. Two other policies are included: 
ACCEPT_ALL
 and 
ACCEPT_NONE
. Implement 
CookiePolicy
 to define a custom policy.

The default CookieManager keeps all accepted cookies in memory. It will forget these cookies when the VM exits. Implement CookieStore to define a custom cookie store.

In addition to the cookies set by HTTP responses, you may set cookies programmatically. To be included in HTTP request headers, cookies must have the domain and path properties set.

By default, new instances of HttpCookie work only with servers that support RFC 2965 cookies. Many web servers support only the older specification, RFC 2109. For compatibility with the most web servers, set the cookie version to 0.

For example, to receive www.twitter.com in French:

   HttpCookie cookie = new HttpCookie("lang", "fr");    cookie.setDomain("twitter.com");    cookie.setPath("/");    cookie.setVersion(0);    cookieManager.getCookieStore().add(new URI("http://twitter.com/"), cookie);  

HTTP Methods

HttpURLConnection uses the GET method by default. It will use POST if setDoOutput(true) has been called. Other HTTP methods (OPTIONS, HEAD, PUT, DELETE and TRACE) can be used with setRequestMethod(String).

Proxies

By default, this class will connect directly to the 
origin server
. It can also connect via an 
HTTP
 or 
SOCKS
 proxy. To use a proxy, use
URL.openConnection(Proxy)
 when creating the connection.

IPv6 Support

This class includes transparent support for IPv6. For hosts with both IPv4 and IPv6 addresses, it will attempt to connect to each of a host‘s addresses until a connection is established.

时间: 2024-10-07 15:07:45

URLConnection的使用的相关文章

URL以及URLConnection对象

java中既然对ip地址都进行了对象的封装,那必须对URL对象进行封装 import java.io.InputStream; import java.net.URL; import java.net.URLConnection; public class URLDemo { public static void main(String[] args) throws Exception { //解析url中的数据,使用URL对象 String str_url = "http://192.168.

java中的URLConnection

*URLConnection是个抽象类,它有两个直接子类分别是HttpURLConnection和JarURLConnection.另外一个重要的类是URL,通常URL可以通过传给构造器一个String类型的参数来生成一个指向特定地址的URL实例. *url.openConnection()方法返回的肯定是这两个子类中的一个,这是java多态性的一种体现 *按图索骥...在eclipse中按几次F3 1.找到openConnection()方法. 2.找到URL中的handler实例.注:han

java中的URLConnection和HttpURLConnection

1 URL url = new URL(strUrl); 2 URLConnection con = url.openConnection(); 1 URL url = new URL(strUrl); 2 HttpURLConnection con = (HttpURLConnection)url.openConnection();

Android中的网络编程系列(一):URLConnection

转载请注明出处:http://blog.csdn.net/bettarwang/article/details/41229955 URL(Uniform Resource Locator)对象代表统一资源定位器,它是指向互联网资源的指针.URL由协议名.主机.端口和资源路径组件,即满足如下格式: protocol://host:port/path 例如http://kan.sogou.com/dianying/就是一个URL地址. URL提供了多个构造方法用于创建URL对象,同时它提供的主要方法

URLConnection类详解

为了防止无良网站的爬虫抓取文章,特此标识,转载请注明文章出处.LaplaceDemon/SJQ. http://www.cnblogs.com/shijiaqi1066/p/3753224.html URLConnection概述 URLConnection是一个抽象类,表示指向URL指定资源的活动连接. URLConnection类本身依赖于Socket类实现网络连接.一般认为,URLConnection类提供了比Socket类更易于使用.更高级的网络连接抽象.但实际上,大多数程序员都会忽略它

[javaSE] 网络编程(URLConnection)

获取URL对象,new出来,构造参数:String的路径 调用URL对象的openConnection()方法,获取URLConnection对象 调用URLConnection对象的getInputStream()方法,获取输入流InputStream对象 读取输出流 import java.io.InputStream; import java.net.URL; import java.net.URLConnection; public class UrlDemo { /** * @para

JAVA学习第六十三课 — 关于客户端服务端 && URL类 & URLConnection

常见的客户端和服务端 客户端:       浏览器:IE:弹窗口,猎豹:弹窗口,多标签,争强效果 服务端:       服务器:TomCat:1.处理请求 2.给予应答 想让TomCat为我们工作,那么java写的相关类类必须实现interface Serverlet 浏览器强大之处就在于解析能力,众多格式,都可以解析 服务端和客户端原理 自定义服务端: public static void main(String[] args) throws IOException { ServerSocke

网络-URLConnection & URLSession

1.URLConnection // 1. url // 1> 判断text是否以http开头 NSString *urlString = text; if (![text hasPrefix:@"http://"]) { // 2> 拼接URL字符串 urlString = [NSString stringWithFormat:@"http://m.baidu.com/s?word=%@", text]; } // 对于特殊字符,例如空格或者中文都需要

JDK中的URLConnection参数详解

JDK中的URLConnection参数详解 来自:http://www.blogjava.net/supercrsky/articles/247449.html 针对JDK中的URLConnection连接Servlet的问题,网上有虽然有所涉及,但是只是说明了某一个或几个问题,是以FAQ的方式来解决的,而且比较零散,现在对这个类的使用就本人在项目中的使用经验做如下总结: 1:> URL请求的类别: 分为二类,GET与POST请求.二者的区别在于:      a:) get请求可以获取静态页面

网络编程 --- URLConnection --- 读取服务器的数据 --- java

使用URLConnection类获取服务器的数据 抽象类URLConnection表示一个指向指定URL资源的活动连接,它是java协议处理器机制的一部分. URL对象的openConnection()方法就是调用了URLStreamHandler的openConnection()方法. 如有疑问请参考:JAVA网络编程[第三版], 如下图: 怎样获取服务器输出的数据呢?代码如下: import java.io.IOException; import java.io.InputStream; i