HttpURLConnection教程
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:
- Obtain a new
HttpURLConnection
by callingURL.openConnection()
and casting the result toHttpURLConnection
. - 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.
- 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 bygetOutputStream()
. - 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. - Disconnect. Once the response body has been read, the
HttpURLConnection
should be closed by callingdisconnect()
. 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 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. 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 (OPTIONS
, HEAD
, PUT
, DELETE
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.
最新文章
- C++随笔:从Hello World 探秘CoreCLR的内部(1)
- 如何在VS 2010中使用 VS2013的解决方案(转)
- AgileEAS.NET SOA 中间件Web运行容器管理功能已全部开源,欢迎大家下载、使用、反馈
- 3.EasyUI学习总结(三)——easyloader源码分析
- 在 Windows 上遇到非常多 TIME_WAIT 連線時應如何處理
- 剑指offer——变态跳台阶
- [HDU5907]Find Q(水)
- (转).net项目技术选型总结
- HDOJ 1017 A Mathematical Curiosity
- Unix时代的开创者Ken Thompson
- Java就业企业面试问题-ssh框架
- 开发中关于Git那些事
- Swift3中dispatch_once废弃的解决办法
- 1705: 小明在工作(zzuli)
- POJ3321Apple Tree Dfs序 树状数组
- SpringIOC和AOP原理 设计模式
- C#Windows窗体中添加了AxWindowsMediaPlayer的详细用法影响键盘操作的问题
- 手机中SN、MEID、IMEI的意思
- windows下能搭建php-fpm吗 phpstudy
- [ios]ScrollView小结
热门文章
- Linux监測某一时刻对外的IP连接情况
- ubuntu16.04LTS安装软件
- 解决cell切割线不是全屏问题
- NS3网络仿真(12): ICMPv4协议
- 【iOS系列】-iOS查看沙盒文件图文教程(真机+模拟器)
- mongodb Failed to start LSB: An object/document-oriented dat
- PL/SQL Developer导入导出Oracle数据库方法
- Hibernate中二级缓存指的是什么?
- CRM 2011 开发中遇到的问题小结
- Lightoj 1019 - Brush (V)