1.Class Overview

  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();
}
}

2.Secure Communication with HTTPS

  Calling openConnection() on a URL with the "https" scheme will return an HttpsURLConnection, which allows for overriding the defaultHostnameVerifier 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. SeeHttpsURLConnection for more details.

3.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(),

4.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(); OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
writeStream(out); InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
finally {
urlConnection.disconnect();
}
}

5.Performance

  The input and output streams returned by this class are not buffered. Most callers should wrap the returned streams with BufferedInputStreamor 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. Since getContentLength() returns the number of bytes transmitted, you cannot use that method to predict how many bytes can be read from getInputStream(). Instead, read that stream until it is exhausted: when read() returns -1. Gzip compression can be disabled by setting the acceptable encodings in the request header:

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

6.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();
}
}

7.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.

8.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();
cookieManager.getCookieStore().add(new URI("http://twitter.com/"), cookie);

9.HTTP Methods

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

10.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, useURL.openConnection(Proxy) when creating the connection.

11.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.

12.Response Caching

  Android 4.0 (Ice Cream Sandwich, API level 15) includes a response cache. See android.net.http.HttpResponseCache for instructions on enabling HTTP caching in your application.

13.Avoiding Bugs In Earlier Releases

  Prior to Android 2.2 (Froyo), this class had some frustrating bugs. In particular, calling close() on a readable InputStream could poison the connection pool. Work around this by disabling connection pooling:

 private void disableConnectionReuseIfNecessary() {
// Work around pre-Froyo bugs in HTTP connection reuse.
if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) {
System.setProperty("http.keepAlive", "false"); }}

  Each instance of HttpURLConnection may be used for one request/response pair. Instances of this class are not thread safe.

 
 

HttpURLConnection教程的更多相关文章

  1. java http工具类和HttpUrlConnection上传文件分析

    利用java中的HttpUrlConnection上传文件,我们其实只要知道Http协议上传文件的标准格式.那么就可以用任何一门语言来模拟浏览器上传文件.下面有几篇文章从http协议入手介绍了java ...

  2. Android通过webservice连接SQLServer 详细教程(数据库+服务器+客户端)

    http://blog.csdn.net/zhyl8157121/article/details/8169172 目录(?)[-] 项目说明 开发环境的部署 数据库设计 服务器端程序设计Webserv ...

  3. okhttp教程——起步篇

    okhttp教程--起步篇 这篇文章主要总结Android著名网络框架-okhttp的基础使用,后续可能会有关于他的高级使用. okhttp是什么 okhttp是Android端的一个Http客户端, ...

  4. OkHttp使用教程

    Android系统提供了两种HTTP通信类,HttpURLConnection和HttpClient.关于HttpURLConnection和HttpClient的选择>>官方博客尽管Go ...

  5. CAS单点登录(SSO)完整教程

    转:http://blog.csdn.net/frinder/article/details/7969925 CAS单点登录(SSO)完整教程(2012-02-01更新) 一.教程说明 前言 教程目的 ...

  6. HttpClient和HttpURLConnection的使用和区别(下)

    转自来自点击打开链接 接着上一篇,我们继续来分析HttpURLConnection的使用,以及两者的共同点和区别. 目录 用法 HttpURLConnection 区别 引用资料 用法 HttpURL ...

  7. 学习笔记(三)--->《Java 8编程官方参考教程(第9版).pdf》:第十章到十二章学习笔记

    回到顶部 注:本文声明事项. 本博文整理者:刘军 本博文出自于: <Java8 编程官方参考教程>一书 声明:1:转载请标注出处.本文不得作为商业活动.若有违本之,则本人不负法律责任.违法 ...

  8. [转]OkHttp3 最有营养的初级教程

    一.前言 自从Android4.4开始,google已经开始将源码中的HttpURLConnection替换为OkHttp,而在Android6.0之后的SDK中google更是移除了对于HttpCl ...

  9. Android 网络教程: 开始

    原文:Android Networking Tutorial: Getting Started 作者:Eunice Obugyei 译者:kmyhy 从 API 级别 1 开始,网络始终是 Andro ...

随机推荐

  1. Windows7系统下优化固态硬盘

    一.AHCI硬盘模式可提高硬盘性能,确定你的固态硬盘是运行在AHCI模式下,打开“HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Servicesmsahci” ...

  2. Qt Quick 图像处理实例之美图秀秀(附源代码下载)

    在<Qt Quick 之 QML 与 C++ 混合编程具体解释>一文中我们解说了 QML 与 C++ 混合编程的方方面面的内容,这次我们通过一个图像处理应用.再来看一下 QML 与 C++ ...

  3. 数据库分表和分库的原理及基于thinkPHP的实现方法

    为什么要分表,分库: 当我们的数据表数据量,訪问量非常大.或者是使用频繁的时候,一个数据表已经不能承受如此大的数据訪问和存储,所以,为了减轻数据库的负担,加快数据的存储,就须要将一张表分成多张,及将一 ...

  4. 【转载】SOAP协议介绍

    SOAP是用在分散或分布的环境中交换信息的简单的协议,它是一个基于XML的协议,包括三个部分:封装定义了一个描述消息中包含什么内容以及如何处理它们的框架,编码规则用于表示应用程序定义的数据类型的实例, ...

  5. STL源代码剖析——STL算法之set集合算法

    前言 本节介绍set集合的相关算法,各自是并集set_union,差集set_difference,交集set_intersection 和对称差集set_symmetric_difference.这 ...

  6. [转] logback 常用配置详解(序)logback 简介

    转载文章:原文出处:http://aub.iteye.com/blog/1101222 logback 简介 Ceki Gülcü在Java日志领域世界知名.他创造了Log4J ,这个最早的Java日 ...

  7. WPF的WebBrowser屏蔽弹出脚本错误窗体

    WPF自带的WebBrowser在訪问一些有问题的网页时常常跳出非常多提示脚本错误的窗体, 可是WPF没有自带屏蔽这些窗体的方法或属性. 所以网上找来一使用反射的方法来屏蔽弹出脚本错误窗体的方法, 非 ...

  8. 零基础学python-5.1 数字简单介绍

    1.创建数值对象并赋值 a=1#整数 b=1.1#浮点数 c=1.23e5#实数 d=1.23+4.56j#虚数 2.更新数值对象 注意:由于数值对象是不可变,所以与其说更新,还不如说把变量名从一个对 ...

  9. jquery源码学习笔记一:总体结构

    练武不练功,到老一场空.计算机也一样. 计算机的功,就是原理.如果程序员只会使用各种函数,各种框架,而不知其原理,顶多熟练工人而已.知其然,更要知其所以然. jquery我们用得很爽,但它究竟咋实现的 ...

  10. http的session和cookie

    1 http session和http请求之间的关系 http协议是无状态的,一次会话服务端需要处理多次http请求,就算是长连接,也是要发送多次请求的,由于http无状态所有每次的请求都是独立的,服 ...