下面列出了怎么用com.squareup.okhttp.internal.http.StatusLine的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Returns the value of the field corresponding to the {@code fieldName}, or
* null if there is no such field. If the field has multiple values, the
* last value is returned.
*/
@Override public final String getHeaderField(String fieldName) {
try {
return fieldName == null
? StatusLine.get(getResponse().getResponse()).toString()
: getHeaders().get(fieldName);
} catch (IOException e) {
return null;
}
}
@Override public final Map<String, List<String>> getHeaderFields() {
try {
return OkHeaders.toMultimap(getHeaders(),
StatusLine.get(getResponse().getResponse()).toString());
} catch (IOException e) {
return Collections.emptyMap();
}
}
private Socket createHttpProxySocket(InetSocketAddress address, InetSocketAddress proxyAddress,
String proxyUsername, String proxyPassword) throws StatusException {
try {
Socket sock;
// The proxy address may not be resolved
if (proxyAddress.getAddress() != null) {
sock = socketFactory.createSocket(proxyAddress.getAddress(), proxyAddress.getPort());
} else {
sock =
socketFactory.createSocket(proxyAddress.getHostName(), proxyAddress.getPort());
}
sock.setTcpNoDelay(true);
Source source = Okio.source(sock);
BufferedSink sink = Okio.buffer(Okio.sink(sock));
// Prepare headers and request method line
Request proxyRequest = createHttpProxyRequest(address, proxyUsername, proxyPassword);
HttpUrl url = proxyRequest.httpUrl();
String requestLine = String.format("CONNECT %s:%d HTTP/1.1", url.host(), url.port());
// Write request to socket
sink.writeUtf8(requestLine).writeUtf8("\r\n");
for (int i = 0, size = proxyRequest.headers().size(); i < size; i++) {
sink.writeUtf8(proxyRequest.headers().name(i))
.writeUtf8(": ")
.writeUtf8(proxyRequest.headers().value(i))
.writeUtf8("\r\n");
}
sink.writeUtf8("\r\n");
// Flush buffer (flushes socket and sends request)
sink.flush();
// Read status line, check if 2xx was returned
StatusLine statusLine = StatusLine.parse(readUtf8LineStrictUnbuffered(source));
// Drain rest of headers
while (!readUtf8LineStrictUnbuffered(source).equals("")) {}
if (statusLine.code < 200 || statusLine.code >= 300) {
Buffer body = new Buffer();
try {
sock.shutdownOutput();
source.read(body, 1024);
} catch (IOException ex) {
body.writeUtf8("Unable to read body: " + ex.toString());
}
try {
sock.close();
} catch (IOException ignored) {
// ignored
}
String message = String.format(
"Response returned from proxy was not successful (expected 2xx, got %d %s). "
+ "Response body:\n%s",
statusLine.code, statusLine.message, body.readUtf8());
throw Status.UNAVAILABLE.withDescription(message).asException();
}
return sock;
} catch (IOException e) {
throw Status.UNAVAILABLE.withDescription("Failed trying to connect with proxy").withCause(e)
.asException();
}
}