Methods Summary |
---|
public void | addRequestProperty(java.lang.String field, java.lang.String value)
if (connected) {
throw new IllegalAccessError(Msg.getString("K0092")); //$NON-NLS-1$
}
if (field == null) {
throw new NullPointerException();
}
reqHeader.add(field, value);
|
public void | connect()Establishes the connection to the remote HTTP server
Any methods that requires a valid connection to the resource will call
this method implicitly. After the connection is established,
connected is set to true.
if (connected) {
return;
}
if (getFromCache()) {
return;
}
// BEGIN android-changed
// url.toURI(); throws an URISyntaxException if the url contains
// illegal characters in e.g. the query.
// Since the query is not needed for proxy selection, we just create an
// URI that only contains the necessary information.
try {
uri = new URI(url.getProtocol(),
null,
url.getHost(),
url.getPort(),
null,
null,
null);
} catch (URISyntaxException e1) {
throw new IOException(e1.getMessage());
}
// END android-changed
// socket to be used for connection
connection = null;
// try to determine: to use the proxy or not
if (proxy != null) {
// try to make the connection to the proxy
// specified in constructor.
// IOException will be thrown in the case of failure
connection = getHTTPConnection(proxy);
} else {
// Use system-wide ProxySelect to select proxy list,
// then try to connect via elements in the proxy list.
ProxySelector selector = ProxySelector.getDefault();
List<Proxy> proxyList = selector.select(uri);
if (proxyList != null) {
for (Proxy selectedProxy : proxyList) {
if (selectedProxy.type() == Proxy.Type.DIRECT) {
// the same as NO_PROXY
continue;
}
try {
connection = getHTTPConnection(selectedProxy);
proxy = selectedProxy;
break; // connected
} catch (IOException e) {
// failed to connect, tell it to the selector
selector.connectFailed(uri, selectedProxy.address(), e);
}
}
}
}
if (connection == null) {
// make direct connection
connection = getHTTPConnection(null);
}
connection.setSoTimeout(getReadTimeout());
setUpTransportIO(connection);
connected = true;
|
private byte[] | createRequest()
StringBuilder output = new StringBuilder(256);
output.append(method);
output.append(' ");
output.append(requestString());
output.append(' ");
output.append("HTTP/1."); //$NON-NLS-1$
if (httpVersion == 0) {
output.append("0\r\n"); //$NON-NLS-1$
} else {
output.append("1\r\n"); //$NON-NLS-1$
}
if (reqHeader.get("User-Agent") == null) { //$NON-NLS-1$
output.append("User-Agent: "); //$NON-NLS-1$
String agent = getSystemProperty("http.agent"); //$NON-NLS-1$
if (agent == null) {
output.append("Java"); //$NON-NLS-1$
output.append(getSystemProperty("java.version")); //$NON-NLS-1$
} else {
output.append(agent);
}
output.append("\r\n"); //$NON-NLS-1$
}
if (reqHeader.get("Host") == null) { //$NON-NLS-1$
output.append("Host: "); //$NON-NLS-1$
output.append(url.getHost());
int port = url.getPort();
if (port > 0 && port != defaultPort) {
output.append(':");
output.append(Integer.toString(port));
}
output.append("\r\n"); //$NON-NLS-1$
}
if (httpVersion > 0 && reqHeader.get("Connection") == null) { //$NON-NLS-1$
output.append("Connection: Keep-Alive\r\n"); //$NON-NLS-1$
}
// if we are doing output make sure the appropriate headers are sent
if (os != null) {
if (reqHeader.get("Content-Type") == null) { //$NON-NLS-1$
output.append("Content-Type: application/x-www-form-urlencoded\r\n"); //$NON-NLS-1$
}
if (os.isCached()) {
if (reqHeader.get("Content-Length") == null) { //$NON-NLS-1$
output.append("Content-Length: "); //$NON-NLS-1$
output.append(Integer.toString(os.size()));
output.append("\r\n"); //$NON-NLS-1$
}
} else if (os.isChunked()) {
output.append("Transfer-Encoding: chunked\r\n"); //$NON-NLS-1$
}
}
boolean hasContentLength = false;
// then the user-specified request headers, if any
for (int i = 0; i < reqHeader.length(); i++) {
String key = reqHeader.getKey(i);
if (key != null) {
String lKey = key.toLowerCase();
if ((os != null && !os.isChunked())
|| (!lKey.equals("transfer-encoding") && !lKey //$NON-NLS-1$
.equals("content-length"))) { //$NON-NLS-1$
output.append(key);
output.append(": "); //$NON-NLS-1$
/*
* duplicates are allowed under certain conditions see
* http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
*/
if (lKey.equals("content-length")) { //$NON-NLS-1$
hasContentLength = true;
/*
* if both setFixedLengthStreamingMode and
* content-length are set, use fixedContentLength first
*/
output.append((fixedContentLength >= 0) ? String
.valueOf(fixedContentLength)
: reqHeader.get(i));
} else {
output.append(reqHeader.get(i));
}
output.append("\r\n"); //$NON-NLS-1$
}
}
}
if (fixedContentLength >= 0 && !hasContentLength) {
output.append("content-length: "); //$NON-NLS-1$
output.append(String.valueOf(fixedContentLength));
output.append("\r\n"); //$NON-NLS-1$
}
// end the headers
output.append("\r\n"); //$NON-NLS-1$
return output.toString().getBytes("ISO8859_1"); //$NON-NLS-1$
|
private synchronized void | disconnect(boolean closeSocket)
if (connection != null) {
if (closeSocket || ((os != null) && !os.closed)) {
/*
* In addition to closing the socket if explicitly
* requested to do so, we also close it if there was
* an output stream associated with the request and it
* wasn't cleanly closed.
*/
connection.closeSocketAndStreams();
} else {
HttpConnectionManager.getDefault().returnConnectionToPool(
connection);
}
connection = null;
}
/*
* Clear "is" and "os" to ensure that no further I/O attempts
* from this instance make their way to the underlying
* connection (which may get recycled).
*/
is = null;
os = null;
|
public void | disconnect()Closes the connection with the HTTP server
disconnect(true);
|
protected void | doRequest()Handles an HTTP request along with its redirects and authentication
// do nothing if we've already sent the request
if (sentRequest) {
// If necessary, finish the request by
// closing the uncached output stream.
if (resHeader == null && os != null) {
os.close();
readServerResponse();
getContentStream();
}
return;
}
doRequestInternal();
|
void | doRequestInternal()
int redirect = 0;
while (true) {
// send the request and process the results
if (!sendRequest()) {
return;
}
// proxy authorization failed ?
if (responseCode == HTTP_PROXY_AUTH) {
if (!usingProxy()) {
// KA017=Received HTTP_PROXY_AUTH (407) code while not using
// proxy
throw new IOException(Msg.getString("KA017")); //$NON-NLS-1$
}
// username/password
// until authorized
String challenge = resHeader.get("Proxy-Authenticate"); //$NON-NLS-1$
if (challenge == null) {
// KA016=Received authentication challenge is null.
throw new IOException(Msg.getString("KA016")); //$NON-NLS-1$
}
// drop everything and reconnect, might not be required for
// HTTP/1.1
endRequest();
disconnect();
connected = false;
String credentials = getAuthorizationCredentials(challenge);
if (credentials == null) {
// could not find credentials, end request cycle
break;
}
// set up the authorization credentials
setRequestProperty("Proxy-Authorization", credentials); //$NON-NLS-1$
// continue to send request
continue;
}
// HTTP authorization failed ?
if (responseCode == HTTP_UNAUTHORIZED) {
// keep asking for username/password until authorized
String challenge = resHeader.get("WWW-Authenticate"); //$NON-NLS-1$
if (challenge == null) {
// KA018=Received authentication challenge is null
throw new IOException(Msg.getString("KA018")); //$NON-NLS-1$
}
// drop everything and reconnect, might not be required for
// HTTP/1.1
endRequest();
disconnect();
connected = false;
String credentials = getAuthorizationCredentials(challenge);
if (credentials == null) {
// could not find credentials, end request cycle
break;
}
// set up the authorization credentials
setRequestProperty("Authorization", credentials); //$NON-NLS-1$
// continue to send request
continue;
}
/*
* See if there is a server redirect to the URL, but only handle 1
* level of URL redirection from the server to avoid being caught in
* an infinite loop
*/
if (getInstanceFollowRedirects()) {
if ((responseCode == HTTP_MULT_CHOICE
|| responseCode == HTTP_MOVED_PERM
|| responseCode == HTTP_MOVED_TEMP
|| responseCode == HTTP_SEE_OTHER || responseCode == HTTP_USE_PROXY)
&& os == null) {
if (++redirect > 4) {
throw new ProtocolException(Msg.getString("K0093")); //$NON-NLS-1$
}
String location = getHeaderField("Location"); //$NON-NLS-1$
if (location != null) {
// start over
if (responseCode == HTTP_USE_PROXY) {
int start = 0;
if (location.startsWith(url.getProtocol() + ':")) {
start = url.getProtocol().length() + 1;
}
if (location.startsWith("//", start)) { //$NON-NLS-1$
start += 2;
}
setProxy(location.substring(start));
} else {
url = new URL(url, location);
hostName = url.getHost();
// update the port
hostPort = -1;
}
endRequest();
disconnect();
connected = false;
continue;
}
}
}
break;
}
// Cache the content stream and read the first chunked header
getContentStream();
|
protected void | endRequest()
if (os != null) {
os.close();
}
sentRequest = false;
|
private java.lang.String | getAuthorizationCredentials(java.lang.String challenge)Returns the authorization credentials on the base of provided
authorization challenge
int idx = challenge.indexOf(" "); //$NON-NLS-1$
String scheme = challenge.substring(0, idx);
int realm = challenge.indexOf("realm=\"") + 7; //$NON-NLS-1$
String prompt = null;
if (realm != -1) {
int end = challenge.indexOf('"", realm);
if (end != -1) {
prompt = challenge.substring(realm, end);
}
}
// The following will use the user-defined authenticator to get
// the password
PasswordAuthentication pa = Authenticator
.requestPasswordAuthentication(getHostAddress(), getHostPort(),
url.getProtocol(), prompt, scheme);
if (pa == null) {
// could not retrieve the credentials
return null;
}
// base64 encode the username and password
byte[] bytes = (pa.getUserName() + ":" + new String(pa.getPassword())) //$NON-NLS-1$
.getBytes("ISO8859_1"); //$NON-NLS-1$
String encoded = Base64.encode(bytes, "ISO8859_1"); //$NON-NLS-1$
return scheme + " " + encoded; //$NON-NLS-1$
|
private java.io.InputStream | getContentStream()
if (uis != null) {
return uis;
}
String encoding = resHeader.get("Transfer-Encoding"); //$NON-NLS-1$
if (encoding != null && encoding.toLowerCase().equals("chunked")) { //$NON-NLS-1$
return uis = new ChunkedInputStream();
}
String sLength = resHeader.get("Content-Length"); //$NON-NLS-1$
if (sLength != null) {
try {
int length = Integer.parseInt(sLength);
return uis = new LimitedInputStream(length);
} catch (NumberFormatException e) {
}
}
// BEGIN android-changed
/*
* Wrap the input stream from the HttpConnection (rather than
* just returning "is" directly here), so that we can control
* its use after the reference escapes.
*/
return uis = new LocalCloseInputStream();
// END android-changed
|
public static java.lang.String | getDefaultRequestProperty(java.lang.String field)Returns the default value for the field specified by field ,
null if there's no such a field.
return defaultReqHeader.get(field);
|
public java.io.InputStream | getErrorStream()Returns an input stream from the server in the case of error such as the
requested file (txt, htm, html) is not found on the remote server.
If the content type is not what stated above,
FileNotFoundException is thrown.
if (connected && method != HEAD && responseCode >= HTTP_BAD_REQUEST) {
return uis;
}
return null;
|
private boolean | getFromCache()
if (useCaches && null != responseCache && !hasTriedCache) {
hasTriedCache = true;
if (null == resHeader) {
resHeader = new Header();
}
cacheResponse = responseCache.get(uri, method, resHeader
.getFieldMap());
if (null != cacheResponse) {
Map<String, List<String>> headMap = cacheResponse.getHeaders();
if (null != headMap) {
resHeader = new Header(headMap);
}
is = cacheResponse.getBody();
if (null != is) {
return true;
}
}
}
if (hasTriedCache && null != is) {
return true;
}
return false;
|
protected HttpConnection | getHTTPConnection(java.net.Proxy proxy)Returns connected socket to be used for this HTTP connection.
HttpConnection connection;
if (proxy == null || proxy.type() == Proxy.Type.DIRECT) {
this.proxy = null; // not using proxy
connection = HttpConnectionManager.getDefault().getConnection(uri, getConnectTimeout());
} else {
connection = HttpConnectionManager.getDefault().getConnection(uri, proxy, getConnectTimeout());
}
return connection;
|
public java.lang.String | getHeaderField(int pos)Returns the value of the field at position pos.
Returns null if there is fewer than pos fields
in the response header.
try {
getInputStream();
} catch (IOException e) {
// ignore
}
if (null == resHeader) {
return null;
}
return resHeader.get(pos);
|
public java.lang.String | getHeaderField(java.lang.String key)Returns the value of the field corresponding to the key
Returns null if there is no such field.
If there are multiple fields with that key, the last field value is
returned.
try {
getInputStream();
} catch (IOException e) {
// ignore
}
if (null == resHeader) {
return null;
}
return resHeader.get(key);
|
public java.lang.String | getHeaderFieldKey(int pos)
try {
getInputStream();
} catch (IOException e) {
// ignore
}
if (null == resHeader) {
return null;
}
return resHeader.getKey(pos);
|
public java.util.Map | getHeaderFields()Provides an unmodifiable map of the connection header values. The map
keys are the String header field names. Each map value is a list of the
header field values associated with that key name.
try {
// ensure that resHeader exists
getInputStream();
} catch (IOException e) {
// ignore
}
if (null == resHeader) {
return null;
}
return resHeader.getFieldMap();
|
private java.net.InetAddress | getHostAddress()Get the InetAddress of the connection machine. This is either the address
given in the URL or the address of the proxy server.
if (hostAddress == null) {
// the value was not set yet
if (proxy != null && proxy.type() != Proxy.Type.DIRECT) {
hostAddress = ((InetSocketAddress) proxy.address())
.getAddress();
} else {
hostAddress = InetAddress.getByName(url.getHost());
}
}
return hostAddress;
|
private java.lang.String | getHostName()Get the hostname of the connection machine. This is either the name given
in the URL or the name of the proxy server.
if (hostName == null) {
// the value was not set yet
if (proxy != null) {
hostName = ((InetSocketAddress) proxy.address()).getHostName();
} else {
hostName = url.getHost();
}
}
return hostName;
|
private int | getHostPort()Get the connection port. This is either the URL's port or the proxy port
if a proxy port has been set.
if (hostPort < 0) {
// the value was not set yet
if (proxy != null) {
hostPort = ((InetSocketAddress) proxy.address()).getPort();
} else {
hostPort = url.getPort();
}
if (hostPort < 0) {
hostPort = defaultPort;
}
}
return hostPort;
|
public java.io.InputStream | getInputStream()
if (!doInput) {
throw new ProtocolException(Msg.getString("K008d")); //$NON-NLS-1$
}
// connect before sending requests
connect();
doRequest();
/*
* if the requested file does not exist, throw an exception formerly the
* Error page from the server was returned if the requested file was
* text/html this has changed to return FileNotFoundException for all
* file types
*/
if (responseCode >= HTTP_BAD_REQUEST) {
throw new FileNotFoundException(url.toString());
}
return uis;
|
public java.io.OutputStream | getOutputStream()
if (!doOutput) {
throw new ProtocolException(Msg.getString("K008e")); //$NON-NLS-1$
}
// you can't write after you read
if (sentRequest) {
throw new ProtocolException(Msg.getString("K0090")); //$NON-NLS-1$
}
if (os != null) {
return os;
}
// they are requesting a stream to write to. This implies a POST method
if (method == GET) {
method = POST;
}
// If the request method is neither PUT or POST, then you're not writing
if (method != PUT && method != POST) {
throw new ProtocolException(Msg.getString("K008f", method)); //$NON-NLS-1$
}
int limit = -1;
String contentLength = reqHeader.get("Content-Length"); //$NON-NLS-1$
if (contentLength != null) {
limit = Integer.parseInt(contentLength);
}
String encoding = reqHeader.get("Transfer-Encoding"); //$NON-NLS-1$
if (httpVersion > 0 && encoding != null) {
encoding = encoding.toLowerCase();
if ("chunked".equals(encoding)) { //$NON-NLS-1$
sendChunked = true;
limit = -1;
}
}
// if user has set chunk/fixedLength mode, use that value
if (chunkLength > 0) {
sendChunked = true;
limit = -1;
}
if (fixedContentLength >= 0) {
limit = fixedContentLength;
}
if ((httpVersion > 0 && sendChunked) || limit >= 0) {
os = new HttpOutputStream(limit);
doRequest();
return os;
}
if (!connected) {
// connect and see if there is cache available.
connect();
}
return os = new HttpOutputStream();
|
public java.security.Permission | getPermission()
return new SocketPermission(getHostName() + ":" + getHostPort(), //$NON-NLS-1$
"connect, resolve"); //$NON-NLS-1$
|
public java.util.Map | getRequestProperties()
if (connected) {
throw new IllegalStateException(Msg.getString("K0091")); //$NON-NLS-1$
}
return reqHeader.getFieldMap();
|
public java.lang.String | getRequestProperty(java.lang.String field)
if (null == field) {
return null;
}
return reqHeader.get(field);
|
public int | getResponseCode()
// Response Code Sample : "HTTP/1.0 200 OK"
// Call connect() first since getHeaderField() doesn't return exceptions
connect();
doRequest();
if (responseCode != -1) {
return responseCode;
}
String response = resHeader.getStatusLine();
if (response == null || !response.startsWith("HTTP/")) { //$NON-NLS-1$
return -1;
}
response = response.trim();
int mark = response.indexOf(" ") + 1; //$NON-NLS-1$
if (mark == 0) {
return -1;
}
if (response.charAt(mark - 2) != '1") {
httpVersion = 0;
}
int last = mark + 3;
if (last > response.length()) {
last = response.length();
}
responseCode = Integer.parseInt(response.substring(mark, last));
if (last + 1 <= response.length()) {
responseMessage = response.substring(last + 1);
}
return responseCode;
|
private java.lang.String | getSystemProperty(java.lang.String property)
return AccessController.doPrivileged(new PriviAction<String>(property));
|
private void | putToCache()
if (useCaches && null != responseCache) {
cacheRequest = responseCache.put(uri, this);
if (null != cacheRequest) {
cacheOut = cacheRequest.getBody();
}
}
|
void | readHeaders()
// parse the result headers until the first blank line
String line;
while (((line = readln()) != null) && (line.length() > 1)) {
// Header parsing
int idx;
if ((idx = line.indexOf(":")) < 0) { //$NON-NLS-1$
resHeader.add("", line.trim()); //$NON-NLS-1$
} else {
resHeader.add(line.substring(0, idx), line.substring(idx + 1)
.trim());
}
}
|
void | readServerResponse()
socketOut.flush();
do {
responseCode = -1;
responseMessage = null;
resHeader = new Header();
String line = readln();
// Add the response, it may contain ':' which we ignore
if (line != null) {
resHeader.setStatusLine(line.trim());
readHeaders();
}
} while (getResponseCode() == 100);
if (method == HEAD || (responseCode >= 100 && responseCode < 200)
|| responseCode == HTTP_NO_CONTENT
|| responseCode == HTTP_NOT_MODIFIED) {
disconnect();
uis = new LimitedInputStream(0);
}
putToCache();
|
java.lang.String | readln()Returns a line read from the input stream. Does not include the \n
boolean lastCr = false;
StringBuffer result = new StringBuffer(80);
int c = is.read();
if (c < 0) {
return null;
}
while (c != '\n") {
if (lastCr) {
result.append('\r");
lastCr = false;
}
if (c == '\r") {
lastCr = true;
} else {
result.append((char) c);
}
c = is.read();
if (c < 0) {
break;
}
}
return result.toString();
|
protected java.lang.String | requestString()
if (usingProxy() || proxyName != null) {
return url.toString();
}
String file = url.getFile();
if (file == null || file.length() == 0) {
file = "/"; //$NON-NLS-1$
}
return file;
|
private boolean | sendRequest()Sends the request header to the remote HTTP server Not all of them are
guaranteed to have any effect on the content the server will return,
depending on if the server supports that field.
Examples : Accept: text/*, text/html, text/html;level=1, Accept-Charset:
iso-8859-5, unicode-1-1;q=0.8
byte[] request = createRequest();
// make sure we have a connection
if (!connected) {
connect();
}
if (null != cacheResponse) {
// does not send if already has a response cache
return true;
}
// send out the HTTP request
socketOut.write(request);
sentRequest = true;
// send any output to the socket (i.e. POST data)
if (os != null && os.isCached()) {
socketOut.write(os.toByteArray());
}
if (os == null || os.isCached()) {
readServerResponse();
return true;
}
return false;
|
public static void | setDefaultRequestProperty(java.lang.String field, java.lang.String value)Sets the default request header fields to be sent to the remote server.
This does not affect the current URL Connection, only newly created ones.
defaultReqHeader.add(field, value);
|
public void | setIfModifiedSince(long newValue)A slightly different implementation from this parent's
setIfModifiedSince() Since this HTTP impl supports
IfModifiedSince as one of the header field, the request header is updated
with the new value.
super.setIfModifiedSince(newValue);
// convert from millisecond since epoch to date string
SimpleDateFormat sdf = new SimpleDateFormat(
"E, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US); //$NON-NLS-1$
sdf.setTimeZone(TimeZone.getTimeZone("GMT")); //$NON-NLS-1$
String date = sdf.format(new Date(newValue));
reqHeader.add("If-Modified-Since", date); //$NON-NLS-1$
|
private void | setProxy(java.lang.String proxy)
int index = proxy.indexOf(':");
if (index == -1) {
proxyName = proxy;
hostPort = defaultPort;
} else {
proxyName = proxy.substring(0, index);
String port = proxy.substring(index + 1);
try {
hostPort = Integer.parseInt(port);
} catch (NumberFormatException e) {
throw new IllegalArgumentException(Msg.getString("K00af", port)); //$NON-NLS-1$
}
if (hostPort < 0 || hostPort > 65535) {
throw new IllegalArgumentException(Msg.getString("K00b0")); //$NON-NLS-1$
}
}
|
public void | setRequestProperty(java.lang.String field, java.lang.String newValue)
if (connected) {
throw new IllegalStateException(Msg.getString("K0092")); //$NON-NLS-1$
}
if (field == null) {
throw new NullPointerException();
}
reqHeader.set(field, newValue);
|
protected void | setUpTransportIO(HttpConnection connection)Sets up the data streams used to send request[s] and read response[s].
socketOut = connection.getOutputStream();
is = connection.getInputStream();
|
public boolean | usingProxy()
return (proxy != null && proxy.type() != Proxy.Type.DIRECT);
|