Most visited

Recently visited

Added in API level 1

HttpURLConnection

public abstract class HttpURLConnection
extends URLConnection

java.lang.Object
   ↳ java.net.URLConnection
     ↳ java.net.HttpURLConnection
Known Direct Subclasses


支持HTTP特定功能的URLConnection。 有关详细信息,请参阅the spec

这个班的用途遵循一种模式:

  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.

例如,要检索 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.

如果HTTP响应表明发生了错误,则getInputStream()将抛出IOException 使用getErrorStream()来读取错误响应。 可以使用getHeaderFields()以正常方式读取标题,

Posting Content

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

为了获得最佳性能,你应该叫要么setFixedLengthStreamingMode(int)当车身长度事先已知或setChunkedStreamingMode(int)当它不是。 否则HttpURLConnection将被强制在发送之前将完整的请求主体缓冲在内存中,浪费(可能耗尽)堆并增加延迟。

例如,要执行上传:

   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.

在向服务器传输大量数据或从服务器传输大量数据时,请使用数据流一次限制内存中的数据量。 除非您需要将整个主体一次存储在内存中,否则将其作为流进行处理(而不是将整个主体存储为单个字节数组或字符串)。

为了减少延迟,这个类可以为多个请求/响应对重用相同的底层Socket 因此,HTTP连接可能会保持打开时间超过必要的时间。 调用disconnect()可能会将套接字返回到连接的套接字池。 这种行为可以通过设置被禁用http.keepAlive系统属性设置为false发出任何HTTP请求之前。 可以使用http.maxConnections属性来控制每个服务器将保留多少空闲连接。

默认情况下,该实现HttpURLConnection请求服务器使用gzip压缩,并自动解压缩getInputStream()调用者的getInputStream() Content-Encoding和Content-Length响应头在这种情况下被清除。 通过在请求标头中设置可接受的编码,可以禁用Gzip压缩:

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

设置Accept-Encoding请求头显式禁用自动解压缩并保留响应头; 根据响应的Content-Encoding标头,呼叫者必须根据需要处理解压缩。

getContentLength()返回传输的字节数,不能用于预测压缩数据流可以从getInputStream()读取多少个字节。 相反,读取该流直到耗尽,即read()返回-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.

默认CookieManager保留所有被接受的cookies在内存中。 当VM退出时它会忘记这些cookie。 实施CookieStore以定义自定义Cookie存储。

除了由HTTP响应设置的Cookie之外,您可以通过编程方式设置Cookie。 要包含在HTTP请求标头中,Cookie必须设置域和路径属性。

默认情况下, HttpCookie新实例仅适用于支持RFC 2965 Cookie的服务器。 许多Web服务器仅支持较旧的规范,即RFC 2109 为了与大多数Web服务器兼容,请将cookie版本设置为0。

例如,要以法语接收 www.twitter.com

   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默认使用GET方法。 如果setDoOutput(true) ,它将使用POST 其他HTTP方法( OPTIONSHEADPUTDELETETRACE )可与使用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

这个类包括对IPv6的透明支持。 对于拥有IPv4和IPv6地址的主机,它将尝试连接到每个主机的地址,直到建立连接。

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.

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

每个HttpURLConnection实例都可以用于一个请求/响应对。 这个类的实例不是线程安全的。

Summary

Constants

int HTTP_ACCEPTED

HTTP状态码202:接受。

int HTTP_BAD_GATEWAY

HTTP状态码502:错误的网关。

int HTTP_BAD_METHOD

HTTP状态码405:方法不允许。

int HTTP_BAD_REQUEST

HTTP状态码400:错误的请求。

int HTTP_CLIENT_TIMEOUT

HTTP状态代码408:请求超时。

int HTTP_CONFLICT

HTTP状态码409:冲突。

int HTTP_CREATED

HTTP状态码201:已创建。

int HTTP_ENTITY_TOO_LARGE

HTTP状态码413:请求实体太大。

int HTTP_FORBIDDEN

HTTP状态码403:禁止。

int HTTP_GATEWAY_TIMEOUT

HTTP状态码504:网关超时。

int HTTP_GONE

HTTP状态码410:去。

int HTTP_INTERNAL_ERROR

HTTP状态代码500:内部服务器错误。

int HTTP_LENGTH_REQUIRED

HTTP状态码411:需要的长度。

int HTTP_MOVED_PERM

HTTP状态码301:永久移动。

int HTTP_MOVED_TEMP

HTTP状态码302:临时重定向。

int HTTP_MULT_CHOICE

HTTP状态码300:多种选择。

int HTTP_NOT_ACCEPTABLE

HTTP状态码406:不可接受。

int HTTP_NOT_AUTHORITATIVE

HTTP状态码203:非权威性信息。

int HTTP_NOT_FOUND

HTTP状态码404:未找到。

int HTTP_NOT_IMPLEMENTED

HTTP状态码501:未实现。

int HTTP_NOT_MODIFIED

HTTP状态码304:未修改。

int HTTP_NO_CONTENT

HTTP状态码204:无内容。

int HTTP_OK

HTTP状态码200:确定。

int HTTP_PARTIAL

HTTP状态码206:部分内容。

int HTTP_PAYMENT_REQUIRED

HTTP状态码402:需要付款。

int HTTP_PRECON_FAILED

HTTP状态代码412:先决条件失败。

int HTTP_PROXY_AUTH

HTTP状态码407:需要代理验证。

int HTTP_REQ_TOO_LONG

HTTP状态码414:请求URI太大。

int HTTP_RESET

HTTP状态码205:重置内容。

int HTTP_SEE_OTHER

HTTP状态代码303:请参阅其他。

int HTTP_SERVER_ERROR

这个常数在API级别1中被弃用。它被放错了位置并且不应该存在。

int HTTP_UNAUTHORIZED

HTTP状态码401:未经授权。

int HTTP_UNAVAILABLE

HTTP状态码503:服务不可用。

int HTTP_UNSUPPORTED_TYPE

HTTP状态码415:不支持的媒体类型。

int HTTP_USE_PROXY

HTTP状态代码305:使用代理。

int HTTP_VERSION

HTTP状态代码505:不支持HTTP版本。

Fields

protected int chunkLength

使用分块编码流模式输出时的块长度。

protected int fixedContentLength

使用固定长度流模式时的固定内容长度。

protected long fixedContentLengthLong

使用固定长度流模式时的固定内容长度。

protected boolean instanceFollowRedirects

如果 true ,该协议将自动遵循重定向。

protected String method

HTTP方法(GET,POST,PUT等)。

protected int responseCode

代表三位数HTTP状态码的 int

protected String responseMessage

HTTP响应消息。

Inherited fields

From class java.net.URLConnection

Protected constructors

HttpURLConnection(URL u)

HttpURLConnection的构造函数。

Public methods

abstract void disconnect()

表示在不久的将来,对服务器的其他请求不太可能。

InputStream getErrorStream()

如果连接失败,则返回错误流,但服务器发送有用数据。

static boolean getFollowRedirects()

返回一个 boolean指示是否应该自动跟随HTTP重定向(3xx)。

String getHeaderField(int n)

返回第 n 标题字段的值。

long getHeaderFieldDate(String name, long Default)

返回解析为日期的命名字段的值。

String getHeaderFieldKey(int n)

返回第 n 标题字段的密钥。

boolean getInstanceFollowRedirects()

返回此 HttpURLConnectioninstanceFollowRedirects字段的值。

Permission getPermission()

返回代表连接到目标主机和端口所需权限的 SocketPermission对象。

String getRequestMethod()

获取请求方法。

int getResponseCode()

从HTTP响应消息中获取状态码。

String getResponseMessage()

获取HTTP响应消息(如果有)与服务器的响应代码一起返回。

void setChunkedStreamingMode(int chunklen)

这种方法被用于使HTTP请求正文的流没有进行内部缓冲,当内容长度事先 知道。

void setFixedLengthStreamingMode(int contentLength)

当预先知道内容长度时,此方法用于在不进行内部缓冲的情况下启用HTTP请求体的流式传输。

void setFixedLengthStreamingMode(long contentLength)

当预先知道内容长度时,此方法用于在不进行内部缓冲的情况下启用HTTP请求体的流式传输。

static void setFollowRedirects(boolean set)

应设置此类是否自动跟随HTTP重定向(具有响应代码3xx的请求)。

void setInstanceFollowRedirects(boolean followRedirects)

这个 HttpURLConnection实例应该自动跟随HTTP重定向(带有响应代码3xx的请求)。

void setRequestMethod(String method)

设置URL请求的方法,其中之一:

  • GET
  • POST
  • HEAD
  • OPTIONS
  • PUT
  • DELETE
  • TRACE
are legal, subject to protocol restrictions.

abstract boolean usingProxy()

指示连接是否通过代理。

Inherited methods

From class java.net.URLConnection
From class java.lang.Object

Constants

HTTP_ACCEPTED

Added in API level 1
int HTTP_ACCEPTED

HTTP状态码202:接受。

常量值:202(0x000000ca)

HTTP_BAD_GATEWAY

Added in API level 1
int HTTP_BAD_GATEWAY

HTTP状态码502:错误的网关。

常量值:502(0x000001f6)

HTTP_BAD_METHOD

Added in API level 1
int HTTP_BAD_METHOD

HTTP状态码405:方法不允许。

常量值:405(0x00000195)

HTTP_BAD_REQUEST

Added in API level 1
int HTTP_BAD_REQUEST

HTTP状态码400:错误的请求。

常量值:400(0x00000190)

HTTP_CLIENT_TIMEOUT

Added in API level 1
int HTTP_CLIENT_TIMEOUT

HTTP状态代码408:请求超时。

常量值:408(0x00000198)

HTTP_CONFLICT

Added in API level 1
int HTTP_CONFLICT

HTTP状态码409:冲突。

常数值:409(0x00000199)

HTTP_CREATED

Added in API level 1
int HTTP_CREATED

HTTP状态码201:已创建。

常量值:201(0x000000c9)

HTTP_ENTITY_TOO_LARGE

Added in API level 1
int HTTP_ENTITY_TOO_LARGE

HTTP状态码413:请求实体太大。

常量值:413(0x0000019d)

HTTP_FORBIDDEN

Added in API level 1
int HTTP_FORBIDDEN

HTTP状态码403:禁止。

常量值:403(0x00000193)

HTTP_GATEWAY_TIMEOUT

Added in API level 1
int HTTP_GATEWAY_TIMEOUT

HTTP状态码504:网关超时。

常量值:504(0x000001f8)

HTTP_GONE

Added in API level 1
int HTTP_GONE

HTTP状态码410:去。

常量值:410(0x0000019a)

HTTP_INTERNAL_ERROR

Added in API level 1
int HTTP_INTERNAL_ERROR

HTTP状态代码500:内部服务器错误。

常量值:500(0x000001f4)

HTTP_LENGTH_REQUIRED

Added in API level 1
int HTTP_LENGTH_REQUIRED

HTTP状态码411:需要的长度。

常量值:411(0x0000019b)

HTTP_MOVED_PERM

Added in API level 1
int HTTP_MOVED_PERM

HTTP状态码301:永久移动。

常量值:301(0x0000012d)

HTTP_MOVED_TEMP

Added in API level 1
int HTTP_MOVED_TEMP

HTTP状态码302:临时重定向。

常量值:302(0x0000012e)

HTTP_MULT_CHOICE

Added in API level 1
int HTTP_MULT_CHOICE

HTTP状态码300:多种选择。

常量值:300(0x0000012c)

HTTP_NOT_ACCEPTABLE

Added in API level 1
int HTTP_NOT_ACCEPTABLE

HTTP状态码406:不可接受。

常量值:406(0x00000196)

HTTP_NOT_AUTHORITATIVE

Added in API level 1
int HTTP_NOT_AUTHORITATIVE

HTTP状态码203:非权威性信息。

常量值:203(0x000000cb)

HTTP_NOT_FOUND

Added in API level 1
int HTTP_NOT_FOUND

HTTP状态码404:未找到。

常量值:404(0x00000194)

HTTP_NOT_IMPLEMENTED

Added in API level 1
int HTTP_NOT_IMPLEMENTED

HTTP状态码501:未实现。

常数值:501(0x000001f5)

HTTP_NOT_MODIFIED

Added in API level 1
int HTTP_NOT_MODIFIED

HTTP状态码304:未修改。

常量值:304(0x00000130)

HTTP_NO_CONTENT

Added in API level 1
int HTTP_NO_CONTENT

HTTP状态码204:无内容。

常量值:204(0x000000cc)

HTTP_OK

Added in API level 1
int HTTP_OK

HTTP状态码200:确定。

常量值:200(0x000000c8)

HTTP_PARTIAL

Added in API level 1
int HTTP_PARTIAL

HTTP状态码206:部分内容。

常量值:206(0x000000ce)

HTTP_PAYMENT_REQUIRED

Added in API level 1
int HTTP_PAYMENT_REQUIRED

HTTP状态码402:需要付款。

常量值:402(0x00000192)

HTTP_PRECON_FAILED

Added in API level 1
int HTTP_PRECON_FAILED

HTTP状态代码412:先决条件失败。

常量值:412(0x0000019c)

HTTP_PROXY_AUTH

Added in API level 1
int HTTP_PROXY_AUTH

HTTP状态码407:需要代理验证。

常量值:407(0x00000197)

HTTP_REQ_TOO_LONG

Added in API level 1
int HTTP_REQ_TOO_LONG

HTTP状态码414:请求URI太大。

常量值:414(0x0000019e)

HTTP_RESET

Added in API level 1
int HTTP_RESET

HTTP状态码205:重置内容。

常量值:205(0x000000cd)

HTTP_SEE_OTHER

Added in API level 1
int HTTP_SEE_OTHER

HTTP状态代码303:请参阅其他。

常量值:303(0x0000012f)

HTTP_SERVER_ERROR

Added in API level 1
int HTTP_SERVER_ERROR

此常数在API级别1中已弃用。
它是错位的,不应该存在。

HTTP状态代码500:内部服务器错误。

常量值:500(0x000001f4)

HTTP_UNAUTHORIZED

Added in API level 1
int HTTP_UNAUTHORIZED

HTTP状态码401:未经授权。

常量值:401(0x00000191)

HTTP_UNAVAILABLE

Added in API level 1
int HTTP_UNAVAILABLE

HTTP状态码503:服务不可用。

常量值:503(0x000001f7)

HTTP_UNSUPPORTED_TYPE

Added in API level 1
int HTTP_UNSUPPORTED_TYPE

HTTP状态码415:不支持的媒体类型。

常量值:415(0x0000019f)

HTTP_USE_PROXY

Added in API level 1
int HTTP_USE_PROXY

HTTP状态代码305:使用代理。

常量值:305(0x00000131)

HTTP_VERSION

Added in API level 1
int HTTP_VERSION

HTTP状态代码505:不支持HTTP版本。

常量值:505(0x000001f9)

Fields

chunkLength

Added in API level 1
int chunkLength

使用分块编码流模式输出时的块长度。 值为-1表示分块编码禁用输出。

fixedContentLength

Added in API level 1
int fixedContentLength

使用固定长度流模式时的固定内容长度。 值为-1表示固定长度流模式已禁用输出。

注意:建议使用 fixedContentLengthLong而不是此字段,因为它允许设置更大的内容长度。

fixedContentLengthLong

Added in API level 19
long fixedContentLengthLong

使用固定长度流模式时的固定内容长度。 值为-1表示固定长度流模式已禁用输出。

instanceFollowRedirects

Added in API level 1
boolean instanceFollowRedirects

如果true ,协议将自动遵循重定向。 如果false ,协议不会自动遵循重定向。

该字段由setInstanceFollowRedirects方法设置。 其值由getInstanceFollowRedirects方法返回。

它的默认值是基于HttpURLConnection构建时的静态followRedirects的值。

也可以看看:

method

Added in API level 1
String method

HTTP方法(GET,POST,PUT等)。

responseCode

Added in API level 1
int responseCode

代表三位数HTTP状态码的 int

  • 1xx: Informational
  • 2xx: Success
  • 3xx: Redirection
  • 4xx: Client Error
  • 5xx: Server Error

responseMessage

Added in API level 1
String responseMessage

HTTP响应消息。

Protected constructors

HttpURLConnection

Added in API level 1
HttpURLConnection (URL u)

HttpURLConnection的构造函数。

Parameters
u URL: the URL

Public methods

disconnect

Added in API level 1
void disconnect ()

表示在不久的将来,对服务器的其他请求不太可能。 调用disconnect()不应该暗示此HttpURLConnection实例可以重用于其他请求。

getErrorStream

Added in API level 1
InputStream getErrorStream ()

如果连接失败,则返回错误流,但服务器发送有用数据。 典型的例子是当一个HTTP服务器响应一个404,这将导致连接中抛出FileNotFoundException,但是服务器发送了一个HTML帮助页面,提供了关于该怎么做的建议。

此方法不会导致启动连接。 如果连接未连接,或者连接时服务器没有错误,或者服务器发生错误但未发送错误数据,则此方法将返回空值。 这是默认设置。

Returns
InputStream an error stream if any, null if there have been no errors, the connection is not connected or the server sent no useful data.

getFollowRedirects

Added in API level 1
boolean getFollowRedirects ()

返回一个 boolean指示是否应该自动遵循HTTP重定向(3xx)。

Returns
boolean true if HTTP redirects should be automatically followed, false if not.

也可以看看:

getHeaderField

Added in API level 1
String getHeaderField (int n)

返回第n 标题字段的值。 某些实现可能0 th标头字段视为特殊字段,即作为HTTP服务器返回的状态行。

此方法可以与 getHeaderFieldKey方法一起使用,以迭代消息中的所有标题。

Parameters
n int: an index, where n>=0.
Returns
String the value of the nth header field, or null if the value does not exist.

也可以看看:

getHeaderFieldDate

Added in API level 1
long getHeaderFieldDate (String name, 
                long Default)

返回解析为日期的命名字段的值。 结果是1970年1月1日以来的毫秒数,由命名字段表示。

这种形式的getHeaderField存在,因为某些连接类型(例如, http-ng )具有预解析的标头。 该连接类型的类可以覆盖此方法并短路解析。

Parameters
name String: the name of the header field.
Default long: a default value.
Returns
long the value of the field, parsed as a date. The value of the Default argument is returned if the field is missing or malformed.

getHeaderFieldKey

Added in API level 1
String getHeaderFieldKey (int n)

返回n th标题字段的密钥。 某些实现可能0 th标题字段视为特殊字段,即作为HTTP服务器返回的状态行。 在这种情况下, getHeaderField(0)返回状态行,但getHeaderFieldKey(0)返回null。

Parameters
n int: an index, where n >=0.
Returns
String the key for the nth header field, or null if the key does not exist.

getInstanceFollowRedirects

Added in API level 1
boolean getInstanceFollowRedirects ()

返回此 HttpURLConnectioninstanceFollowRedirects字段的值。

Returns
boolean the value of this HttpURLConnection's instanceFollowRedirects field.

也可以看看:

getPermission

Added in API level 1
Permission getPermission ()

返回表示连接到目标主机和端口所需权限的 SocketPermission对象。

Returns
Permission a SocketPermission object representing the permission necessary to connect to the destination host and port.
Throws
IOException if an error occurs while computing the permission.

getRequestMethod

Added in API level 1
String getRequestMethod ()

获取请求方法。

Returns
String the HTTP request method

也可以看看:

getResponseCode

Added in API level 1
int getResponseCode ()

从HTTP响应消息中获取状态码。 例如,在以下状态行的情况下:

 HTTP/1.0 200 OK
 HTTP/1.0 401 Unauthorized
 
It will return 200 and 401 respectively. Returns -1 if no code can be discerned from the response (i.e., the response is not valid HTTP).

Returns
int the HTTP Status-Code, or -1
Throws
IOException if an error occurred connecting to the server.

getResponseMessage

Added in API level 1
String getResponseMessage ()

获取HTTP响应消息(如果有)与服务器的响应代码一起返回。 从类似的回复

 HTTP/1.0 200 OK
 HTTP/1.0 404 Not Found
 
Extracts the Strings "OK" and "Not Found" respectively. Returns null if none could be discerned from the responses (the result was not valid HTTP).

Returns
String the HTTP response message, or null
Throws
IOException if an error occurred connecting to the server.

setChunkedStreamingMode

Added in API level 1
void setChunkedStreamingMode (int chunklen)

这种方法被用于使HTTP请求正文的流没有进行内部缓冲,当内容长度事先知道。 在此模式下,分块传输编码用于发送请求主体。 请注意,并非所有HTTP服务器都支持此模式。

当启用输出流时,不能自动处理认证和重定向。 如果需要验证或重定向,则在读取响应时将抛出HttpRetryException。 这个异常可以查询错误的细节。

该方法必须在URLConnection连接之前调用。

Parameters
chunklen int: The number of bytes to write in each chunk. If chunklen is less than or equal to zero, a default value will be used.
Throws
IllegalStateException if URLConnection is already connected or if a different streaming mode is already enabled.

也可以看看:

setFixedLengthStreamingMode

Added in API level 1
void setFixedLengthStreamingMode (int contentLength)

当预先知道内容长度时,此方法用于在不进行内部缓冲的情况下启用HTTP请求体的流式传输。

如果应用程序试图写入比指定的内容长度更多的数据,或者应用程序在写入指定的数量之前关闭了OutputStream,则会抛出异常。

当启用输出流时,不能自动处理认证和重定向。 如果需要验证或重定向,则在读取响应时将抛出HttpRetryException。 这个异常可以查询错误的细节。

该方法必须在URLConnection连接之前调用。

注意:建议使用 setFixedLengthStreamingMode(long)而不是此方法,因为它允许设置更大的内容长度。

Parameters
contentLength int: The number of bytes which will be written to the OutputStream.
Throws
IllegalStateException if URLConnection is already connected or if a different streaming mode is already enabled.
IllegalArgumentException if a content length less than zero is specified.

也可以看看:

setFixedLengthStreamingMode

Added in API level 19
void setFixedLengthStreamingMode (long contentLength)

当预先知道内容长度时,此方法用于在不进行内部缓冲的情况下启用HTTP请求体的流式传输。

如果应用程序试图写入比指定的内容长度更多的数据,或者应用程序在写入指定的数量之前关闭了OutputStream,则会抛出异常。

当启用输出流时,不能自动处理认证和重定向。 如果需要验证或重定向,则在读取响应时将引发HttpRetryException 这个异常可以查询错误的细节。

该方法必须在URLConnection连接之前调用。

通过调用此方法设置的内容长度优先于由 setFixedLengthStreamingMode(int)设置的任何值。

Parameters
contentLength long: The number of bytes which will be written to the OutputStream.
Throws
IllegalStateException if URLConnection is already connected or if a different streaming mode is already enabled.
IllegalArgumentException if a content length less than zero is specified.

setFollowRedirects

Added in API level 1
void setFollowRedirects (boolean set)

应设置此类是否自动跟随HTTP重定向(具有响应代码3xx的请求)。 默认情况下为真。 Applets不能改变这个变量。

如果有安全管理器,则此方法首先调用安全管理器的方法checkSetFactory以确保允许操作。 这可能会导致SecurityException。

Parameters
set boolean: a boolean indicating whether or not to follow HTTP redirects.
Throws
SecurityException if a security manager exists and its checkSetFactory method doesn't allow the operation.

也可以看看:

setInstanceFollowRedirects

Added in API level 1
void setInstanceFollowRedirects (boolean followRedirects)

设置此 HttpURLConnection实例是否应该自动跟随HTTP重定向(具有响应代码3xx的请求)。

默认值来自followRedirects,默认值为true。

Parameters
followRedirects boolean: a boolean indicating whether or not to follow HTTP redirects.

也可以看看:

setRequestMethod

Added in API level 1
void setRequestMethod (String method)

设置URL请求的方法,其中之一:

  • GET
  • POST
  • HEAD
  • OPTIONS
  • PUT
  • DELETE
  • TRACE
are legal, subject to protocol restrictions. The default method is GET.

Parameters
method String: the HTTP method
Throws
ProtocolException if the method cannot be reset or if the requested method isn't valid for HTTP.
SecurityException if a security manager is set and the method is "TRACE", but the "allowHttpTrace" NetPermission is not granted.

也可以看看:

usingProxy

Added in API level 1
boolean usingProxy ()

指示连接是否通过代理。

Returns
boolean a boolean indicating if the connection is using a proxy.

Hooray!