Typical implementations will look up a credential and create a request
32 | * derived from the initial request by setting the "Authorization" header.
33 | *
40 | */
41 | Request authenticate(Proxy proxy, Response response) throws IOException;
42 |
43 | /**
44 | * Returns a request that includes a credential to satisfy an authentication
45 | * challenge made by {@code response}. Returns null if the challenge cannot be
46 | * satisfied. This method is called in response to an HTTP 407 unauthorized
47 | * status code sent by the proxy server.
48 | *
49 | *
Typical implementations will look up a credential and create a request
50 | * derived from the initial request by setting the "Proxy-Authorization"
51 | * header.
58 | */
59 | Request authenticateProxy(Proxy proxy, Response response) throws IOException;
60 | }
61 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/Callback.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2014 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package okhttp3;
17 |
18 | import java.io.IOException;
19 |
20 | public interface Callback {
21 | /**
22 | * Called when the request could not be executed due to cancellation, a
23 | * connectivity problem or timeout. Because networks can fail during an
24 | * exchange, it is possible that the remote server accepted the request
25 | * before the failure.
26 | */
27 | void onFailure(Request request, IOException e);
28 |
29 | /**
30 | * Called when the HTTP response was successfully returned by the remote
31 | * server. The callback may proceed to read the response body with {@link
32 | * Response#body}. The response is still live until its response body is
33 | * closed with {@code response.body().close()}. The recipient of the callback
34 | * may even consume the response body on another thread.
35 | *
36 | *
Note that transport-layer success (receiving a HTTP response code,
37 | * headers and body) does not necessarily indicate application-layer
38 | * success: {@code response} may still indicate an unhappy HTTP response
39 | * code like 404 or 500.
40 | */
41 | void onResponse(Response response) throws IOException;
42 | }
43 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/Challenge.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2014 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package okhttp3;
17 |
18 | import okhttp3.internal.Util;
19 |
20 | /** An RFC 2617 challenge. */
21 | public final class Challenge {
22 | private final String scheme;
23 | private final String realm;
24 |
25 | public Challenge(String scheme, String realm) {
26 | this.scheme = scheme;
27 | this.realm = realm;
28 | }
29 |
30 | /** Returns the authentication scheme, like {@code Basic}. */
31 | public String scheme() {
32 | return scheme;
33 | }
34 |
35 | /** Returns the protection space. */
36 | public String realm() {
37 | return realm;
38 | }
39 |
40 | @Override public boolean equals(Object o) {
41 | return o instanceof Challenge
42 | && Util.equal(scheme, ((Challenge) o).scheme)
43 | && Util.equal(realm, ((Challenge) o).realm);
44 | }
45 |
46 | @Override public int hashCode() {
47 | int result = 29;
48 | result = 31 * result + (realm != null ? realm.hashCode() : 0);
49 | result = 31 * result + (scheme != null ? scheme.hashCode() : 0);
50 | return result;
51 | }
52 |
53 | @Override public String toString() {
54 | return scheme + " realm=\"" + realm + "\"";
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/Connection.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one or more
3 | * contributor license agreements. See the NOTICE file distributed with
4 | * this work for additional information regarding copyright ownership.
5 | * The ASF licenses this file to You under the Apache License, Version 2.0
6 | * (the "License"); you may not use this file except in compliance with
7 | * the License. You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 | package okhttp3;
18 |
19 | import java.net.Socket;
20 |
21 | /**
22 | * The sockets and streams of an HTTP, HTTPS, or HTTPS+SPDY connection. May be used for multiple
23 | * HTTP request/response exchanges. Connections may be direct to the origin server or via a proxy.
24 | *
25 | *
Typically instances of this class are created, connected and exercised automatically by the
26 | * HTTP client. Applications may use this class to monitor HTTP connections as members of a
27 | * {@linkplain ConnectionPool connection pool}.
28 | *
29 | *
Do not confuse this class with the misnamed {@code HttpURLConnection}, which isn't so much a
30 | * connection as a single request/response exchange.
31 | *
32 | *
Modern TLS
33 | * There are tradeoffs when selecting which options to include when negotiating a secure connection
34 | * to a remote host. Newer TLS options are quite useful:
35 | *
36 | *
Server Name Indication (SNI) enables one IP address to negotiate secure connections for
37 | * multiple domain names.
38 | *
Application Layer Protocol Negotiation (ALPN) enables the HTTPS port (443) to be used for
39 | * different HTTP and SPDY protocols.
40 | *
41 | * Unfortunately, older HTTPS servers refuse to connect when such options are presented. Rather than
42 | * avoiding these options entirely, this class allows a connection to be attempted with modern
43 | * options and then retried without them should the attempt fail.
44 | *
45 | *
Connection Reuse
46 | *
Each connection can carry a varying number streams, depending on the underlying protocol being
47 | * used. HTTP/1.x connections can carry either zero or one streams. HTTP/2 connections can carry any
48 | * number of streams, dynamically configured with {@code SETTINGS_MAX_CONCURRENT_STREAMS}. A
49 | * connection currently carrying zero streams is an idle stream. We keep it alive because reusing an
50 | * existing connection is typically faster than establishing a new one.
51 | *
52 | *
When a single logical call requires multiple streams due to redirects or authorization
53 | * challenges, we prefer to use the same physical connection for all streams in the sequence. There
54 | * are potential performance and behavior consequences to this preference. To support this feature,
55 | * this class separates allocations from streams. An allocation is created by a call,
56 | * used for one or more streams, and then released. An allocated connection won't be stolen by
57 | * other calls while a redirect or authorization challenge is being handled.
58 | *
59 | *
When the maximum concurrent streams limit is reduced, some allocations will be rescinded.
60 | * Attempting to create new streams on these allocations will fail.
61 | *
62 | *
Note that an allocation may be released before its stream is completed. This is intended to
63 | * make bookkeeping easier for the caller: releasing the allocation as soon as the terminal stream
64 | * has been found. But only complete the stream once its data stream has been exhausted.
65 | */
66 | public interface Connection {
67 | /** Returns the route used by this connection. */
68 | Route getRoute();
69 |
70 | /**
71 | * Returns the socket that this connection uses, or null if the connection
72 | * is not currently connected.
73 | */
74 | Socket getSocket();
75 |
76 | Handshake getHandshake();
77 |
78 | /**
79 | * Returns the protocol negotiated by this connection, or {@link Protocol#HTTP_1_1} if no protocol
80 | * has been negotiated. This method returns {@link Protocol#HTTP_1_1} even if the remote peer is
81 | * using {@link Protocol#HTTP_1_0}.
82 | */
83 | Protocol getProtocol();
84 | }
85 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/Credentials.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2014 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package okhttp3;
17 |
18 | import java.io.UnsupportedEncodingException;
19 | import okio.ByteString;
20 |
21 | /** Factory for HTTP authorization credentials. */
22 | public final class Credentials {
23 | private Credentials() {
24 | }
25 |
26 | /** Returns an auth credential for the Basic scheme. */
27 | public static String basic(String userName, String password) {
28 | try {
29 | String usernameAndPassword = userName + ":" + password;
30 | byte[] bytes = usernameAndPassword.getBytes("ISO-8859-1");
31 | String encoded = ByteString.of(bytes).base64();
32 | return "Basic " + encoded;
33 | } catch (UnsupportedEncodingException e) {
34 | throw new AssertionError();
35 | }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/Dns.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2012 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package okhttp3;
17 |
18 | import java.net.InetAddress;
19 | import java.net.UnknownHostException;
20 | import java.util.Arrays;
21 | import java.util.List;
22 |
23 | /**
24 | * A domain name service that resolves IP addresses for host names. Most applications will use the
25 | * {@linkplain #SYSTEM system DNS service}, which is the default. Some applications may provide
26 | * their own implementation to use a different DNS server, to prefer IPv6 addresses, to prefer IPv4
27 | * addresses, or to force a specific known IP address.
28 | *
29 | *
Implementations of this interface must be safe for concurrent use.
30 | */
31 | public interface Dns {
32 | /**
33 | * A DNS that uses {@link InetAddress#getAllByName} to ask the underlying operating system to
34 | * lookup IP addresses. Most custom {@link Dns} implementations should delegate to this instance.
35 | */
36 | Dns SYSTEM = new Dns() {
37 | @Override public List lookup(String hostname) throws UnknownHostException {
38 | if (hostname == null) throw new UnknownHostException("hostname == null");
39 | return Arrays.asList(InetAddress.getAllByName(hostname));
40 | }
41 | };
42 |
43 | /**
44 | * Returns the IP addresses of {@code hostname}, in the order they will be attempted by OkHttp.
45 | * If a connection to an address fails, OkHttp will retry the connection with the next address
46 | * until either a connection is made, the set of IP addresses is exhausted, or a limit is
47 | * exceeded.
48 | */
49 | List lookup(String hostname) throws UnknownHostException;
50 | }
51 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/FormBody.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2014 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package okhttp3;
17 |
18 | import okhttp3.internal.Util;
19 | import java.io.IOException;
20 | import java.util.ArrayList;
21 | import java.util.List;
22 | import okio.Buffer;
23 | import okio.BufferedSink;
24 |
25 | import static okhttp3.HttpUrl.FORM_ENCODE_SET;
26 | import static okhttp3.HttpUrl.percentDecode;
27 |
28 | public final class FormBody extends RequestBody {
29 | private static final MediaType CONTENT_TYPE =
30 | MediaType.parse("application/x-www-form-urlencoded");
31 |
32 | private final List encodedNames;
33 | private final List encodedValues;
34 |
35 | private FormBody(List encodedNames, List encodedValues) {
36 | this.encodedNames = Util.immutableList(encodedNames);
37 | this.encodedValues = Util.immutableList(encodedValues);
38 | }
39 |
40 | /** The number of key-value pairs in this form-encoded body. */
41 | public int size() {
42 | return encodedNames.size();
43 | }
44 |
45 | public String encodedName(int index) {
46 | return encodedNames.get(index);
47 | }
48 |
49 | public String name(int index) {
50 | return percentDecode(encodedName(index), true);
51 | }
52 |
53 | public String encodedValue(int index) {
54 | return encodedValues.get(index);
55 | }
56 |
57 | public String value(int index) {
58 | return percentDecode(encodedValue(index), true);
59 | }
60 |
61 | @Override public MediaType contentType() {
62 | return CONTENT_TYPE;
63 | }
64 |
65 | @Override public long contentLength() {
66 | return writeOrCountBytes(null, true);
67 | }
68 |
69 | @Override public void writeTo(BufferedSink sink) throws IOException {
70 | writeOrCountBytes(sink, false);
71 | }
72 |
73 | /**
74 | * Either writes this request to {@code sink} or measures its content length. We have one method
75 | * do double-duty to make sure the counting and content are consistent, particularly when it
76 | * comes to awkward operations like measuring the encoded length of header strings, or the
77 | * length-in-digits of an encoded integer.
78 | */
79 | private long writeOrCountBytes(BufferedSink sink, boolean countBytes) {
80 | long byteCount = 0L;
81 |
82 | Buffer buffer;
83 | if (countBytes) {
84 | buffer = new Buffer();
85 | } else {
86 | buffer = sink.buffer();
87 | }
88 |
89 | for (int i = 0, size = encodedNames.size(); i < size; i++) {
90 | if (i > 0) buffer.writeByte('&');
91 | buffer.writeUtf8(encodedNames.get(i));
92 | buffer.writeByte('=');
93 | buffer.writeUtf8(encodedValues.get(i));
94 | }
95 |
96 | if (countBytes) {
97 | byteCount = buffer.size();
98 | buffer.clear();
99 | }
100 |
101 | return byteCount;
102 | }
103 |
104 | public static final class Builder {
105 | private final List names = new ArrayList<>();
106 | private final List values = new ArrayList<>();
107 |
108 | public Builder add(String name, String value) {
109 | names.add(HttpUrl.canonicalize(name, FORM_ENCODE_SET, false, true, true));
110 | values.add(HttpUrl.canonicalize(value, FORM_ENCODE_SET, false, true, true));
111 | return this;
112 | }
113 |
114 | public Builder addEncoded(String name, String value) {
115 | names.add(HttpUrl.canonicalize(name, FORM_ENCODE_SET, true, true, true));
116 | values.add(HttpUrl.canonicalize(value, FORM_ENCODE_SET, true, true, true));
117 | return this;
118 | }
119 |
120 | public FormBody build() {
121 | return new FormBody(names, values);
122 | }
123 | }
124 | }
125 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/Interceptor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2014 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package okhttp3;
17 |
18 | import java.io.IOException;
19 |
20 | /**
21 | * Observes, modifies, and potentially short-circuits requests going out and the corresponding
22 | * requests coming back in. Typically interceptors will be used to add, remove, or transform headers
23 | * on the request or response.
24 | */
25 | public interface Interceptor {
26 | Response intercept(Chain chain) throws IOException;
27 |
28 | interface Chain {
29 | Request request();
30 | Response proceed(Request request) throws IOException;
31 | Connection connection();
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/Protocol.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2014 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package okhttp3;
17 |
18 | import java.io.IOException;
19 |
20 | /**
21 | * Protocols that OkHttp implements for ALPN
23 | * selection.
24 | *
25 | *
Protocol vs Scheme
26 | * Despite its name, {@link java.net.URL#getProtocol()} returns the
27 | * {@linkplain java.net.URI#getScheme() scheme} (http, https, etc.) of the URL, not
28 | * the protocol (http/1.1, spdy/3.1, etc.). OkHttp uses the word protocol
29 | * to identify how HTTP messages are framed.
30 | */
31 | public enum Protocol {
32 | /**
33 | * An obsolete plaintext framing that does not use persistent sockets by
34 | * default.
35 | */
36 | HTTP_1_0("http/1.0"),
37 |
38 | /**
39 | * A plaintext framing that includes persistent connections.
40 | *
41 | *
This version of OkHttp implements RFC 2616, and tracks
43 | * revisions to that spec.
44 | */
45 | HTTP_1_1("http/1.1"),
46 |
47 | /**
48 | * Chromium's binary-framed protocol that includes header compression,
49 | * multiplexing multiple requests on the same socket, and server-push.
50 | * HTTP/1.1 semantics are layered on SPDY/3.
51 | *
52 | *
This version of OkHttp implements SPDY 3 draft
54 | * 3.1. Future releases of OkHttp may use this identifier for a newer draft
55 | * of the SPDY spec.
56 | */
57 | SPDY_3("spdy/3.1"),
58 |
59 | /**
60 | * The IETF's binary-framed protocol that includes header compression,
61 | * multiplexing multiple requests on the same socket, and server-push.
62 | * HTTP/1.1 semantics are layered on HTTP/2.
63 | *
64 | *
HTTP/2 requires deployments of HTTP/2 that use TLS 1.2 support
65 | * {@linkplain CipherSuite#TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256}
66 | * , present in Java 8+ and Android 5+. Servers that enforce this may send an
67 | * exception message including the string {@code INADEQUATE_SECURITY}.
68 | */
69 | HTTP_2("h2");
70 |
71 | private final String protocol;
72 |
73 | Protocol(String protocol) {
74 | this.protocol = protocol;
75 | }
76 |
77 | /**
78 | * Returns the protocol identified by {@code protocol}.
79 | * @throws IOException if {@code protocol} is unknown.
80 | */
81 | public static Protocol get(String protocol) throws IOException {
82 | // Unroll the loop over values() to save an allocation.
83 | if (protocol.equals(HTTP_1_0.protocol)) return HTTP_1_0;
84 | if (protocol.equals(HTTP_1_1.protocol)) return HTTP_1_1;
85 | if (protocol.equals(HTTP_2.protocol)) return HTTP_2;
86 | if (protocol.equals(SPDY_3.protocol)) return SPDY_3;
87 | throw new IOException("Unexpected protocol: " + protocol);
88 | }
89 |
90 | /**
91 | * Returns the string used to identify this protocol for ALPN, like
92 | * "http/1.1", "spdy/3.1" or "h2".
93 | */
94 | @Override public String toString() {
95 | return protocol;
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/RequestBody.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2014 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package okhttp3;
17 |
18 | import okhttp3.internal.Util;
19 | import java.io.File;
20 | import java.io.IOException;
21 | import java.nio.charset.Charset;
22 | import okio.BufferedSink;
23 | import okio.ByteString;
24 | import okio.Okio;
25 | import okio.Source;
26 |
27 | public abstract class RequestBody {
28 | /** Returns the Content-Type header for this body. */
29 | public abstract MediaType contentType();
30 |
31 | /**
32 | * Returns the number of bytes that will be written to {@code out} in a call
33 | * to {@link #writeTo}, or -1 if that count is unknown.
34 | */
35 | public long contentLength() throws IOException {
36 | return -1;
37 | }
38 |
39 | /** Writes the content of this request to {@code out}. */
40 | public abstract void writeTo(BufferedSink sink) throws IOException;
41 |
42 | /**
43 | * Returns a new request body that transmits {@code content}. If {@code
44 | * contentType} is non-null and lacks a charset, this will use UTF-8.
45 | */
46 | public static RequestBody create(MediaType contentType, String content) {
47 | Charset charset = Util.UTF_8;
48 | if (contentType != null) {
49 | charset = contentType.charset();
50 | if (charset == null) {
51 | charset = Util.UTF_8;
52 | contentType = MediaType.parse(contentType + "; charset=utf-8");
53 | }
54 | }
55 | byte[] bytes = content.getBytes(charset);
56 | return create(contentType, bytes);
57 | }
58 |
59 | /** Returns a new request body that transmits {@code content}. */
60 | public static RequestBody create(final MediaType contentType, final ByteString content) {
61 | return new RequestBody() {
62 | @Override public MediaType contentType() {
63 | return contentType;
64 | }
65 |
66 | @Override public long contentLength() throws IOException {
67 | return content.size();
68 | }
69 |
70 | @Override public void writeTo(BufferedSink sink) throws IOException {
71 | sink.write(content);
72 | }
73 | };
74 | }
75 |
76 | /** Returns a new request body that transmits {@code content}. */
77 | public static RequestBody create(final MediaType contentType, final byte[] content) {
78 | return create(contentType, content, 0, content.length);
79 | }
80 |
81 | /** Returns a new request body that transmits {@code content}. */
82 | public static RequestBody create(final MediaType contentType, final byte[] content,
83 | final int offset, final int byteCount) {
84 | if (content == null) throw new NullPointerException("content == null");
85 | Util.checkOffsetAndCount(content.length, offset, byteCount);
86 | return new RequestBody() {
87 | @Override public MediaType contentType() {
88 | return contentType;
89 | }
90 |
91 | @Override public long contentLength() {
92 | return byteCount;
93 | }
94 |
95 | @Override public void writeTo(BufferedSink sink) throws IOException {
96 | sink.write(content, offset, byteCount);
97 | }
98 | };
99 | }
100 |
101 | /** Returns a new request body that transmits the content of {@code file}. */
102 | public static RequestBody create(final MediaType contentType, final File file) {
103 | if (file == null) throw new NullPointerException("content == null");
104 |
105 | return new RequestBody() {
106 | @Override public MediaType contentType() {
107 | return contentType;
108 | }
109 |
110 | @Override public long contentLength() {
111 | return file.length();
112 | }
113 |
114 | @Override public void writeTo(BufferedSink sink) throws IOException {
115 | Source source = null;
116 | try {
117 | source = Okio.source(file);
118 | sink.writeAll(source);
119 | } finally {
120 | Util.closeQuietly(source);
121 | }
122 | }
123 | };
124 | }
125 | }
126 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/Route.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2013 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package okhttp3;
17 |
18 | import java.net.InetSocketAddress;
19 | import java.net.Proxy;
20 |
21 | /**
22 | * The concrete route used by a connection to reach an abstract origin server.
23 | * When creating a connection the client has many options:
24 | *
25 | *
HTTP proxy: a proxy server may be explicitly
26 | * configured for the client. Otherwise the {@linkplain java.net.ProxySelector
27 | * proxy selector} is used. It may return multiple proxies to attempt.
28 | *
IP address: whether connecting directly to an origin
29 | * server or a proxy, opening a socket requires an IP address. The DNS
30 | * server may return multiple IP addresses to attempt.
31 | *
32 | * Each route is a specific selection of these options.
33 | */
34 | public final class Route {
35 | final Address address;
36 | final Proxy proxy;
37 | final InetSocketAddress inetSocketAddress;
38 |
39 | public Route(Address address, Proxy proxy, InetSocketAddress inetSocketAddress) {
40 | if (address == null) {
41 | throw new NullPointerException("address == null");
42 | }
43 | if (proxy == null) {
44 | throw new NullPointerException("proxy == null");
45 | }
46 | if (inetSocketAddress == null) {
47 | throw new NullPointerException("inetSocketAddress == null");
48 | }
49 | this.address = address;
50 | this.proxy = proxy;
51 | this.inetSocketAddress = inetSocketAddress;
52 | }
53 |
54 | public Address address() {
55 | return address;
56 | }
57 |
58 | /**
59 | * Returns the {@link Proxy} of this route.
60 | *
61 | * Warning: This may disagree with {@link Address#proxy}
62 | * when it is null. When the address's proxy is null, the proxy selector is
63 | * used.
64 | */
65 | public Proxy proxy() {
66 | return proxy;
67 | }
68 |
69 | public InetSocketAddress socketAddress() {
70 | return inetSocketAddress;
71 | }
72 |
73 | /**
74 | * Returns true if this route tunnels HTTPS through an HTTP proxy. See RFC 2817, Section 5.2.
76 | */
77 | public boolean requiresTunnel() {
78 | return address.sslSocketFactory != null && proxy.type() == Proxy.Type.HTTP;
79 | }
80 |
81 | @Override public boolean equals(Object obj) {
82 | if (obj instanceof Route) {
83 | Route other = (Route) obj;
84 | return address.equals(other.address)
85 | && proxy.equals(other.proxy)
86 | && inetSocketAddress.equals(other.inetSocketAddress);
87 | }
88 | return false;
89 | }
90 |
91 | @Override public int hashCode() {
92 | int result = 17;
93 | result = 31 * result + address.hashCode();
94 | result = 31 * result + proxy.hashCode();
95 | result = 31 * result + inetSocketAddress.hashCode();
96 | return result;
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/TlsVersion.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2014 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package okhttp3;
17 |
18 | import javax.net.ssl.SSLSocket;
19 |
20 | /**
21 | * Versions of TLS that can be offered when negotiating a secure socket. See
22 | * {@link SSLSocket#setEnabledProtocols}.
23 | */
24 | public enum TlsVersion {
25 | TLS_1_2("TLSv1.2"), // 2008.
26 | TLS_1_1("TLSv1.1"), // 2006.
27 | TLS_1_0("TLSv1"), // 1999.
28 | SSL_3_0("SSLv3"), // 1996.
29 | ;
30 |
31 | final String javaName;
32 |
33 | TlsVersion(String javaName) {
34 | this.javaName = javaName;
35 | }
36 |
37 | public static TlsVersion forJavaName(String javaName) {
38 | switch (javaName) {
39 | case "TLSv1.2": return TLS_1_2;
40 | case "TLSv1.1": return TLS_1_1;
41 | case "TLSv1": return TLS_1_0;
42 | case "SSLv3": return SSL_3_0;
43 | }
44 | throw new IllegalArgumentException("Unexpected TLS version: " + javaName);
45 | }
46 |
47 | public String javaName() {
48 | return javaName;
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/internal/FaultHidingSink.java:
--------------------------------------------------------------------------------
1 | package okhttp3.internal;
2 |
3 | import java.io.IOException;
4 | import okio.Buffer;
5 | import okio.ForwardingSink;
6 | import okio.Sink;
7 |
8 | /** A sink that never throws IOExceptions, even if the underlying sink does. */
9 | class FaultHidingSink extends ForwardingSink {
10 | private boolean hasErrors;
11 |
12 | public FaultHidingSink(Sink delegate) {
13 | super(delegate);
14 | }
15 |
16 | @Override public void write(Buffer source, long byteCount) throws IOException {
17 | if (hasErrors) {
18 | source.skip(byteCount);
19 | return;
20 | }
21 | try {
22 | super.write(source, byteCount);
23 | } catch (IOException e) {
24 | hasErrors = true;
25 | onException(e);
26 | }
27 | }
28 |
29 | @Override public void flush() throws IOException {
30 | if (hasErrors) return;
31 | try {
32 | super.flush();
33 | } catch (IOException e) {
34 | hasErrors = true;
35 | onException(e);
36 | }
37 | }
38 |
39 | @Override public void close() throws IOException {
40 | if (hasErrors) return;
41 | try {
42 | super.close();
43 | } catch (IOException e) {
44 | hasErrors = true;
45 | onException(e);
46 | }
47 | }
48 |
49 | protected void onException(IOException e) {
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/internal/Internal.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2014 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package okhttp3.internal;
17 |
18 | import okhttp3.Address;
19 | import okhttp3.Call;
20 | import okhttp3.Callback;
21 | import okhttp3.ConnectionPool;
22 | import okhttp3.ConnectionSpec;
23 | import okhttp3.Headers;
24 | import okhttp3.HttpUrl;
25 | import okhttp3.OkHttpClient;
26 | import okhttp3.internal.http.StreamAllocation;
27 | import okhttp3.internal.io.RealConnection;
28 | import java.net.MalformedURLException;
29 | import java.net.UnknownHostException;
30 | import java.util.logging.Logger;
31 | import javax.net.ssl.SSLSocket;
32 |
33 | /**
34 | * Escalate internal APIs in {@code okhttp3} so they can be used from OkHttp's implementation
35 | * packages. The only implementation of this interface is in {@link OkHttpClient}.
36 | */
37 | public abstract class Internal {
38 | public static final Logger logger = Logger.getLogger(OkHttpClient.class.getName());
39 |
40 | public static void initializeInstanceForTests() {
41 | // Needed in tests to ensure that the instance is actually pointing to something.
42 | new OkHttpClient();
43 | }
44 |
45 | public static Internal instance;
46 |
47 | public abstract void addLenient(Headers.Builder builder, String line);
48 |
49 | public abstract void addLenient(Headers.Builder builder, String name, String value);
50 |
51 | public abstract void setCache(OkHttpClient client, InternalCache internalCache);
52 |
53 | public abstract InternalCache internalCache(OkHttpClient client);
54 |
55 | public abstract RealConnection get(
56 | ConnectionPool pool, Address address, StreamAllocation streamAllocation);
57 |
58 | public abstract void put(ConnectionPool pool, RealConnection connection);
59 |
60 | public abstract boolean connectionBecameIdle(ConnectionPool pool, RealConnection connection);
61 |
62 | public abstract RouteDatabase routeDatabase(ConnectionPool connectionPool);
63 |
64 | public abstract void apply(ConnectionSpec tlsConfiguration, SSLSocket sslSocket,
65 | boolean isFallback);
66 |
67 | public abstract HttpUrl getHttpUrlChecked(String url)
68 | throws MalformedURLException, UnknownHostException;
69 |
70 | // TODO delete the following when web sockets move into the main package.
71 | public abstract void callEnqueue(Call call, Callback responseCallback, boolean forWebSocket);
72 | public abstract StreamAllocation callEngineGetStreamAllocation(Call call);
73 | }
74 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/internal/InternalCache.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2013 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package okhttp3.internal;
17 |
18 | import okhttp3.Request;
19 | import okhttp3.Response;
20 | import okhttp3.internal.http.CacheRequest;
21 | import okhttp3.internal.http.CacheStrategy;
22 | import java.io.IOException;
23 | import okhttp3.Cache;
24 |
25 | /**
26 | * OkHttp's internal cache interface. Applications shouldn't implement this:
27 | * instead use {@link Cache}.
28 | */
29 | public interface InternalCache {
30 | Response get(Request request) throws IOException;
31 |
32 | CacheRequest put(Response response) throws IOException;
33 |
34 | /**
35 | * Remove any cache entries for the supplied {@code request}. This is invoked
36 | * when the client invalidates the cache, such as when making POST requests.
37 | */
38 | void remove(Request request) throws IOException;
39 |
40 | /**
41 | * Handles a conditional request hit by updating the stored cache response
42 | * with the headers from {@code network}. The cached response body is not
43 | * updated. If the stored response has changed since {@code cached} was
44 | * returned, this does nothing.
45 | */
46 | void update(Response cached, Response network) throws IOException;
47 |
48 | /** Track an conditional GET that was satisfied by this cache. */
49 | void trackConditionalCacheHit();
50 |
51 | /** Track an HTTP response being satisfied with {@code cacheStrategy}. */
52 | void trackResponse(CacheStrategy cacheStrategy);
53 | }
54 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/internal/NamedRunnable.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2013 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package okhttp3.internal;
18 |
19 | /**
20 | * Runnable implementation which always sets its thread name.
21 | */
22 | public abstract class NamedRunnable implements Runnable {
23 | protected final String name;
24 |
25 | public NamedRunnable(String format, Object... args) {
26 | this.name = String.format(format, args);
27 | }
28 |
29 | @Override public final void run() {
30 | String oldName = Thread.currentThread().getName();
31 | Thread.currentThread().setName(name);
32 | try {
33 | execute();
34 | } finally {
35 | Thread.currentThread().setName(oldName);
36 | }
37 | }
38 |
39 | protected abstract void execute();
40 | }
41 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/internal/RouteDatabase.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2013 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package okhttp3.internal;
17 |
18 | import okhttp3.Route;
19 | import java.util.LinkedHashSet;
20 | import java.util.Set;
21 |
22 | /**
23 | * A blacklist of failed routes to avoid when creating a new connection to a
24 | * target address. This is used so that OkHttp can learn from its mistakes: if
25 | * there was a failure attempting to connect to a specific IP address or proxy
26 | * server, that failure is remembered and alternate routes are preferred.
27 | */
28 | public final class RouteDatabase {
29 | private final Set failedRoutes = new LinkedHashSet<>();
30 |
31 | /** Records a failure connecting to {@code failedRoute}. */
32 | public synchronized void failed(Route failedRoute) {
33 | failedRoutes.add(failedRoute);
34 | }
35 |
36 | /** Records success connecting to {@code failedRoute}. */
37 | public synchronized void connected(Route route) {
38 | failedRoutes.remove(route);
39 | }
40 |
41 | /** Returns true if {@code route} has failed recently and should be avoided. */
42 | public synchronized boolean shouldPostpone(Route route) {
43 | return failedRoutes.contains(route);
44 | }
45 |
46 | public synchronized int failedRoutesCount() {
47 | return failedRoutes.size();
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/internal/Version.java:
--------------------------------------------------------------------------------
1 | package okhttp3.internal;
2 |
3 | /**
4 | * Created by huxq17 on 2015/12/17.
5 | */
6 | public final class Version {
7 | public static String userAgent() {
8 | return "okhttp/${project.version}";
9 | }
10 |
11 | private Version() {
12 | }
13 | }
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/internal/framed/ErrorCode.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2013 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package okhttp3.internal.framed;
17 |
18 | // http://tools.ietf.org/html/draft-ietf-httpbis-http2-17#section-7
19 | public enum ErrorCode {
20 | /** Not an error! For SPDY stream resets, prefer null over NO_ERROR. */
21 | NO_ERROR(0, -1, 0),
22 |
23 | PROTOCOL_ERROR(1, 1, 1),
24 |
25 | /** A subtype of PROTOCOL_ERROR used by SPDY. */
26 | INVALID_STREAM(1, 2, -1),
27 |
28 | /** A subtype of PROTOCOL_ERROR used by SPDY. */
29 | UNSUPPORTED_VERSION(1, 4, -1),
30 |
31 | /** A subtype of PROTOCOL_ERROR used by SPDY. */
32 | STREAM_IN_USE(1, 8, -1),
33 |
34 | /** A subtype of PROTOCOL_ERROR used by SPDY. */
35 | STREAM_ALREADY_CLOSED(1, 9, -1),
36 |
37 | INTERNAL_ERROR(2, 6, 2),
38 |
39 | FLOW_CONTROL_ERROR(3, 7, -1),
40 |
41 | STREAM_CLOSED(5, -1, -1),
42 |
43 | FRAME_TOO_LARGE(6, 11, -1),
44 |
45 | REFUSED_STREAM(7, 3, -1),
46 |
47 | CANCEL(8, 5, -1),
48 |
49 | COMPRESSION_ERROR(9, -1, -1),
50 |
51 | CONNECT_ERROR(10, -1, -1),
52 |
53 | ENHANCE_YOUR_CALM(11, -1, -1),
54 |
55 | INADEQUATE_SECURITY(12, -1, -1),
56 |
57 | HTTP_1_1_REQUIRED(13, -1, -1),
58 |
59 | INVALID_CREDENTIALS(-1, 10, -1);
60 |
61 | public final int httpCode;
62 | public final int spdyRstCode;
63 | public final int spdyGoAwayCode;
64 |
65 | private ErrorCode(int httpCode, int spdyRstCode, int spdyGoAwayCode) {
66 | this.httpCode = httpCode;
67 | this.spdyRstCode = spdyRstCode;
68 | this.spdyGoAwayCode = spdyGoAwayCode;
69 | }
70 |
71 | public static ErrorCode fromSpdy3Rst(int code) {
72 | for (ErrorCode errorCode : ErrorCode.values()) {
73 | if (errorCode.spdyRstCode == code) return errorCode;
74 | }
75 | return null;
76 | }
77 |
78 | public static ErrorCode fromHttp2(int code) {
79 | for (ErrorCode errorCode : ErrorCode.values()) {
80 | if (errorCode.httpCode == code) return errorCode;
81 | }
82 | return null;
83 | }
84 |
85 | public static ErrorCode fromSpdyGoAway(int code) {
86 | for (ErrorCode errorCode : ErrorCode.values()) {
87 | if (errorCode.spdyGoAwayCode == code) return errorCode;
88 | }
89 | return null;
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/internal/framed/Header.java:
--------------------------------------------------------------------------------
1 | package okhttp3.internal.framed;
2 |
3 | import okio.ByteString;
4 |
5 | /** HTTP header: the name is an ASCII string, but the value can be UTF-8. */
6 | public final class Header {
7 | // Special header names defined in the SPDY and HTTP/2 specs.
8 | public static final ByteString RESPONSE_STATUS = ByteString.encodeUtf8(":status");
9 | public static final ByteString TARGET_METHOD = ByteString.encodeUtf8(":method");
10 | public static final ByteString TARGET_PATH = ByteString.encodeUtf8(":path");
11 | public static final ByteString TARGET_SCHEME = ByteString.encodeUtf8(":scheme");
12 | public static final ByteString TARGET_AUTHORITY = ByteString.encodeUtf8(":authority"); // HTTP/2
13 | public static final ByteString TARGET_HOST = ByteString.encodeUtf8(":host"); // spdy/3
14 | public static final ByteString VERSION = ByteString.encodeUtf8(":version"); // spdy/3
15 |
16 | /** Name in case-insensitive ASCII encoding. */
17 | public final ByteString name;
18 | /** Value in UTF-8 encoding. */
19 | public final ByteString value;
20 | final int hpackSize;
21 |
22 | // TODO: search for toLowerCase and consider moving logic here.
23 | public Header(String name, String value) {
24 | this(ByteString.encodeUtf8(name), ByteString.encodeUtf8(value));
25 | }
26 |
27 | public Header(ByteString name, String value) {
28 | this(name, ByteString.encodeUtf8(value));
29 | }
30 |
31 | public Header(ByteString name, ByteString value) {
32 | this.name = name;
33 | this.value = value;
34 | this.hpackSize = 32 + name.size() + value.size();
35 | }
36 |
37 | @Override public boolean equals(Object other) {
38 | if (other instanceof Header) {
39 | Header that = (Header) other;
40 | return this.name.equals(that.name)
41 | && this.value.equals(that.value);
42 | }
43 | return false;
44 | }
45 |
46 | @Override public int hashCode() {
47 | int result = 17;
48 | result = 31 * result + name.hashCode();
49 | result = 31 * result + value.hashCode();
50 | return result;
51 | }
52 |
53 | @Override public String toString() {
54 | return String.format("%s: %s", name.utf8(), value.utf8());
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/internal/framed/HeadersMode.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2013 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package okhttp3.internal.framed;
17 |
18 | public enum HeadersMode {
19 | SPDY_SYN_STREAM,
20 | SPDY_REPLY,
21 | SPDY_HEADERS,
22 | HTTP_20_HEADERS;
23 |
24 | /** Returns true if it is an error these headers to create a new stream. */
25 | public boolean failIfStreamAbsent() {
26 | return this == SPDY_REPLY || this == SPDY_HEADERS;
27 | }
28 |
29 | /** Returns true if it is an error these headers to update an existing stream. */
30 | public boolean failIfStreamPresent() {
31 | return this == SPDY_SYN_STREAM;
32 | }
33 |
34 | /**
35 | * Returns true if it is an error these headers to be the initial headers of a
36 | * response.
37 | */
38 | public boolean failIfHeadersAbsent() {
39 | return this == SPDY_HEADERS;
40 | }
41 |
42 | /**
43 | * Returns true if it is an error these headers to be update existing headers
44 | * of a response.
45 | */
46 | public boolean failIfHeadersPresent() {
47 | return this == SPDY_REPLY;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/internal/framed/Ping.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2012 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package okhttp3.internal.framed;
17 |
18 | import java.util.concurrent.CountDownLatch;
19 | import java.util.concurrent.TimeUnit;
20 |
21 | /**
22 | * A locally-originated ping.
23 | */
24 | public final class Ping {
25 | private final CountDownLatch latch = new CountDownLatch(1);
26 | private long sent = -1;
27 | private long received = -1;
28 |
29 | Ping() {
30 | }
31 |
32 | void send() {
33 | if (sent != -1) throw new IllegalStateException();
34 | sent = System.nanoTime();
35 | }
36 |
37 | void receive() {
38 | if (received != -1 || sent == -1) throw new IllegalStateException();
39 | received = System.nanoTime();
40 | latch.countDown();
41 | }
42 |
43 | void cancel() {
44 | if (received != -1 || sent == -1) throw new IllegalStateException();
45 | received = sent - 1;
46 | latch.countDown();
47 | }
48 |
49 | /**
50 | * Returns the round trip time for this ping in nanoseconds, waiting for the
51 | * response to arrive if necessary. Returns -1 if the response was
52 | * canceled.
53 | */
54 | public long roundTripTime() throws InterruptedException {
55 | latch.await();
56 | return received - sent;
57 | }
58 |
59 | /**
60 | * Returns the round trip time for this ping in nanoseconds, or -1 if the
61 | * response was canceled, or -2 if the timeout elapsed before the round
62 | * trip completed.
63 | */
64 | public long roundTripTime(long timeout, TimeUnit unit) throws InterruptedException {
65 | if (latch.await(timeout, unit)) {
66 | return received - sent;
67 | } else {
68 | return -2;
69 | }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/internal/framed/PushObserver.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2014 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package okhttp3.internal.framed;
17 |
18 | import java.io.IOException;
19 | import java.util.List;
20 | import okhttp3.Protocol;
21 | import okio.BufferedSource;
22 |
23 | /**
24 | * {@link Protocol#HTTP_2 HTTP/2} only.
25 | * Processes server-initiated HTTP requests on the client. Implementations must
26 | * quickly dispatch callbacks to avoid creating a bottleneck.
27 | *
28 | *
While {@link #onReset} may occur at any time, the following callbacks are
29 | * expected in order, correlated by stream ID.
30 | *
31 | *
{@link #onRequest}
32 | *
{@link #onHeaders} (unless canceled)
33 | *
{@link #onData} (optional sequence of data frames)
34 | *
35 | *
36 | *
As a stream ID is scoped to a single HTTP/2 connection, implementations
37 | * which target multiple connections should expect repetition of stream IDs.
38 | *
39 | *
Return true to request cancellation of a pushed stream. Note that this
40 | * does not guarantee future frames won't arrive on the stream ID.
41 | */
42 | public interface PushObserver {
43 | /**
44 | * Describes the request that the server intends to push a response for.
45 | *
46 | * @param streamId server-initiated stream ID: an even number.
47 | * @param requestHeaders minimally includes {@code :method}, {@code :scheme},
48 | * {@code :authority}, and (@code :path}.
49 | */
50 | boolean onRequest(int streamId, List requestHeaders);
51 |
52 | /**
53 | * The response headers corresponding to a pushed request. When {@code last}
54 | * is true, there are no data frames to follow.
55 | *
56 | * @param streamId server-initiated stream ID: an even number.
57 | * @param responseHeaders minimally includes {@code :status}.
58 | * @param last when true, there is no response data.
59 | */
60 | boolean onHeaders(int streamId, List responseHeaders, boolean last);
61 |
62 | /**
63 | * A chunk of response data corresponding to a pushed request. This data
64 | * must either be read or skipped.
65 | *
66 | * @param streamId server-initiated stream ID: an even number.
67 | * @param source location of data corresponding with this stream ID.
68 | * @param byteCount number of bytes to read or skip from the source.
69 | * @param last when true, there are no data frames to follow.
70 | */
71 | boolean onData(int streamId, BufferedSource source, int byteCount, boolean last)
72 | throws IOException;
73 |
74 | /** Indicates the reason why this stream was canceled. */
75 | void onReset(int streamId, ErrorCode errorCode);
76 |
77 | PushObserver CANCEL = new PushObserver() {
78 |
79 | @Override public boolean onRequest(int streamId, List requestHeaders) {
80 | return true;
81 | }
82 |
83 | @Override public boolean onHeaders(int streamId, List responseHeaders, boolean last) {
84 | return true;
85 | }
86 |
87 | @Override public boolean onData(int streamId, BufferedSource source, int byteCount,
88 | boolean last) throws IOException {
89 | source.skip(byteCount);
90 | return true;
91 | }
92 |
93 | @Override public void onReset(int streamId, ErrorCode errorCode) {
94 | }
95 | };
96 | }
97 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/internal/framed/Variant.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2013 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package okhttp3.internal.framed;
17 |
18 | import okhttp3.Protocol;
19 | import okio.BufferedSink;
20 | import okio.BufferedSource;
21 |
22 | /** A version and dialect of the framed socket protocol. */
23 | public interface Variant {
24 |
25 | /** The protocol as selected using ALPN. */
26 | Protocol getProtocol();
27 |
28 | /**
29 | * @param client true if this is the HTTP client's reader, reading frames from a server.
30 | */
31 | FrameReader newReader(BufferedSource source, boolean client);
32 |
33 | /**
34 | * @param client true if this is the HTTP client's writer, writing frames to a server.
35 | */
36 | FrameWriter newWriter(BufferedSink sink, boolean client);
37 | }
38 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/internal/http/AuthenticatorAdapter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2013 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package okhttp3.internal.http;
17 |
18 | import okhttp3.Authenticator;
19 | import okhttp3.Challenge;
20 | import okhttp3.Credentials;
21 | import okhttp3.HttpUrl;
22 | import okhttp3.Request;
23 | import okhttp3.Response;
24 | import java.io.IOException;
25 | import java.net.Authenticator.RequestorType;
26 | import java.net.InetAddress;
27 | import java.net.InetSocketAddress;
28 | import java.net.PasswordAuthentication;
29 | import java.net.Proxy;
30 | import java.util.List;
31 |
32 | /** Adapts {@link java.net.Authenticator} to {@link Authenticator}. */
33 | public final class AuthenticatorAdapter implements Authenticator {
34 | /** Uses the global authenticator to get the password. */
35 | public static final Authenticator INSTANCE = new AuthenticatorAdapter();
36 |
37 | @Override public Request authenticate(Proxy proxy, Response response) throws IOException {
38 | List challenges = response.challenges();
39 | Request request = response.request();
40 | HttpUrl url = request.url();
41 | for (int i = 0, size = challenges.size(); i < size; i++) {
42 | Challenge challenge = challenges.get(i);
43 | if (!"Basic".equalsIgnoreCase(challenge.scheme())) continue;
44 |
45 | PasswordAuthentication auth = java.net.Authenticator.requestPasswordAuthentication(
46 | url.host(), getConnectToInetAddress(proxy, url), url.port(), url.scheme(),
47 | challenge.realm(), challenge.scheme(), url.url(), RequestorType.SERVER);
48 | if (auth == null) continue;
49 |
50 | String credential = Credentials.basic(auth.getUserName(), new String(auth.getPassword()));
51 | return request.newBuilder()
52 | .header("Authorization", credential)
53 | .build();
54 | }
55 | return null;
56 |
57 | }
58 |
59 | @Override public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
60 | List challenges = response.challenges();
61 | Request request = response.request();
62 | HttpUrl url = request.url();
63 | for (int i = 0, size = challenges.size(); i < size; i++) {
64 | Challenge challenge = challenges.get(i);
65 | if (!"Basic".equalsIgnoreCase(challenge.scheme())) continue;
66 |
67 | InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();
68 | PasswordAuthentication auth = java.net.Authenticator.requestPasswordAuthentication(
69 | proxyAddress.getHostName(), getConnectToInetAddress(proxy, url), proxyAddress.getPort(),
70 | url.scheme(), challenge.realm(), challenge.scheme(), url.url(),
71 | RequestorType.PROXY);
72 | if (auth == null) continue;
73 |
74 | String credential = Credentials.basic(auth.getUserName(), new String(auth.getPassword()));
75 | return request.newBuilder()
76 | .header("Proxy-Authorization", credential)
77 | .build();
78 | }
79 | return null;
80 | }
81 |
82 | private InetAddress getConnectToInetAddress(Proxy proxy, HttpUrl url) throws IOException {
83 | return (proxy != null && proxy.type() != Proxy.Type.DIRECT)
84 | ? ((InetSocketAddress) proxy.address()).getAddress()
85 | : InetAddress.getByName(url.host());
86 | }
87 | }
88 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/internal/http/CacheRequest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2014 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package okhttp3.internal.http;
17 |
18 | import java.io.IOException;
19 | import okio.Sink;
20 |
21 | public interface CacheRequest {
22 | Sink body() throws IOException;
23 | void abort();
24 | }
25 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/internal/http/HeaderParser.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2011 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package okhttp3.internal.http;
18 |
19 | public final class HeaderParser {
20 | /**
21 | * Returns the next index in {@code input} at or after {@code pos} that
22 | * contains a character from {@code characters}. Returns the input length if
23 | * none of the requested characters can be found.
24 | */
25 | public static int skipUntil(String input, int pos, String characters) {
26 | for (; pos < input.length(); pos++) {
27 | if (characters.indexOf(input.charAt(pos)) != -1) {
28 | break;
29 | }
30 | }
31 | return pos;
32 | }
33 |
34 | /**
35 | * Returns the next non-whitespace character in {@code input} that is white
36 | * space. Result is undefined if input contains newline characters.
37 | */
38 | public static int skipWhitespace(String input, int pos) {
39 | for (; pos < input.length(); pos++) {
40 | char c = input.charAt(pos);
41 | if (c != ' ' && c != '\t') {
42 | break;
43 | }
44 | }
45 | return pos;
46 | }
47 |
48 | /**
49 | * Returns {@code value} as a positive integer, or 0 if it is negative, or
50 | * {@code defaultValue} if it cannot be parsed.
51 | */
52 | public static int parseSeconds(String value, int defaultValue) {
53 | try {
54 | long seconds = Long.parseLong(value);
55 | if (seconds > Integer.MAX_VALUE) {
56 | return Integer.MAX_VALUE;
57 | } else if (seconds < 0) {
58 | return 0;
59 | } else {
60 | return (int) seconds;
61 | }
62 | } catch (NumberFormatException e) {
63 | return defaultValue;
64 | }
65 | }
66 |
67 | private HeaderParser() {
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/internal/http/HttpMethod.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2014 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package okhttp3.internal.http;
17 |
18 | public final class HttpMethod {
19 | public static boolean invalidatesCache(String method) {
20 | return method.equals("POST")
21 | || method.equals("PATCH")
22 | || method.equals("PUT")
23 | || method.equals("DELETE")
24 | || method.equals("MOVE"); // WebDAV
25 | }
26 |
27 | public static boolean requiresRequestBody(String method) {
28 | return method.equals("POST")
29 | || method.equals("PUT")
30 | || method.equals("PATCH")
31 | || method.equals("PROPPATCH") // WebDAV
32 | || method.equals("REPORT"); // CalDAV/CardDAV (defined in WebDAV Versioning)
33 | }
34 |
35 | public static boolean permitsRequestBody(String method) {
36 | return requiresRequestBody(method)
37 | || method.equals("OPTIONS")
38 | || method.equals("DELETE") // Permitted as spec is ambiguous.
39 | || method.equals("PROPFIND") // (WebDAV) without body: request
40 | || method.equals("MKCOL") // (WebDAV) may contain a body, but behaviour is unspecified
41 | || method.equals("LOCK"); // (WebDAV) body: create lock, without body: refresh lock
42 | }
43 |
44 | public static boolean redirectsToGet(String method) {
45 | // All requests but PROPFIND should redirect to a GET request.
46 | return !method.equals("PROPFIND");
47 | }
48 |
49 | private HttpMethod() {
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/internal/http/HttpStream.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2012 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package okhttp3.internal.http;
18 |
19 | import okhttp3.Request;
20 | import okhttp3.Response;
21 | import okhttp3.ResponseBody;
22 | import java.io.IOException;
23 | import okio.Sink;
24 |
25 | public interface HttpStream {
26 | /**
27 | * The timeout to use while discarding a stream of input data. Since this is
28 | * used for connection reuse, this timeout should be significantly less than
29 | * the time it takes to establish a new connection.
30 | */
31 | int DISCARD_STREAM_TIMEOUT_MILLIS = 100;
32 |
33 | /** Returns an output stream where the request body can be streamed. */
34 | Sink createRequestBody(Request request, long contentLength) throws IOException;
35 |
36 | /** This should update the HTTP engine's sentRequestMillis field. */
37 | void writeRequestHeaders(Request request) throws IOException;
38 |
39 | /**
40 | * Sends the request body returned by {@link #createRequestBody} to the
41 | * remote peer.
42 | */
43 | void writeRequestBody(RetryableSink requestBody) throws IOException;
44 |
45 | /** Flush the request to the underlying socket. */
46 | void finishRequest() throws IOException;
47 |
48 | /** Read and return response headers. */
49 | Response.Builder readResponseHeaders() throws IOException;
50 |
51 | /** Returns a stream that reads the response body. */
52 | ResponseBody openResponseBody(Response response) throws IOException;
53 |
54 | void setHttpEngine(HttpEngine httpEngine);
55 |
56 | /**
57 | * Cancel this stream. Resources held by this stream will be cleaned up, though not synchronously.
58 | * That may happen later by the connection pool thread.
59 | */
60 | void cancel();
61 | }
62 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/internal/http/RealResponseBody.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2014 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package okhttp3.internal.http;
17 |
18 | import okhttp3.Headers;
19 | import okhttp3.MediaType;
20 | import okhttp3.ResponseBody;
21 | import okio.BufferedSource;
22 |
23 | public final class RealResponseBody extends ResponseBody {
24 | private final Headers headers;
25 | private final BufferedSource source;
26 |
27 | public RealResponseBody(Headers headers, BufferedSource source) {
28 | this.headers = headers;
29 | this.source = source;
30 | }
31 |
32 | @Override public MediaType contentType() {
33 | String contentType = headers.get("Content-Type");
34 | return contentType != null ? MediaType.parse(contentType) : null;
35 | }
36 |
37 | @Override public long contentLength() {
38 | return OkHeaders.contentLength(headers);
39 | }
40 |
41 | @Override public BufferedSource source() {
42 | return source;
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/internal/http/RequestException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package okhttp3.internal.http;
17 |
18 | import java.io.IOException;
19 |
20 | /**
21 | * Indicates a problem with interpreting a request. It may indicate there was a problem with the
22 | * request itself, or the environment being used to interpret the request (network failure, etc.).
23 | */
24 | public final class RequestException extends Exception {
25 |
26 | public RequestException(IOException cause) {
27 | super(cause);
28 | }
29 |
30 | @Override
31 | public IOException getCause() {
32 | return (IOException) super.getCause();
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/internal/http/RequestLine.java:
--------------------------------------------------------------------------------
1 | package okhttp3.internal.http;
2 |
3 | import okhttp3.HttpUrl;
4 | import okhttp3.Request;
5 | import java.net.HttpURLConnection;
6 | import java.net.Proxy;
7 |
8 | public final class RequestLine {
9 | private RequestLine() {
10 | }
11 |
12 | /**
13 | * Returns the request status line, like "GET / HTTP/1.1". This is exposed
14 | * to the application by {@link HttpURLConnection#getHeaderFields}, so it
15 | * needs to be set even if the transport is SPDY.
16 | */
17 | static String get(Request request, Proxy.Type proxyType) {
18 | StringBuilder result = new StringBuilder();
19 | result.append(request.method());
20 | result.append(' ');
21 |
22 | if (includeAuthorityInRequestLine(request, proxyType)) {
23 | result.append(request.url());
24 | } else {
25 | result.append(requestPath(request.url()));
26 | }
27 |
28 | result.append(" HTTP/1.1");
29 | return result.toString();
30 | }
31 |
32 | /**
33 | * Returns true if the request line should contain the full URL with host
34 | * and port (like "GET http://android.com/foo HTTP/1.1") or only the path
35 | * (like "GET /foo HTTP/1.1").
36 | */
37 | private static boolean includeAuthorityInRequestLine(Request request, Proxy.Type proxyType) {
38 | return !request.isHttps() && proxyType == Proxy.Type.HTTP;
39 | }
40 |
41 | /**
42 | * Returns the path to request, like the '/' in 'GET / HTTP/1.1'. Never empty,
43 | * even if the request URL is. Includes the query component if it exists.
44 | */
45 | public static String requestPath(HttpUrl url) {
46 | String path = url.encodedPath();
47 | String query = url.encodedQuery();
48 | return query != null ? (path + '?' + query) : path;
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/internal/http/RetryableSink.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2010 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package okhttp3.internal.http;
18 |
19 | import java.io.IOException;
20 | import java.net.ProtocolException;
21 | import okio.Buffer;
22 | import okio.Sink;
23 | import okio.Timeout;
24 |
25 | import static okhttp3.internal.Util.checkOffsetAndCount;
26 |
27 | /**
28 | * An HTTP request body that's completely buffered in memory. This allows
29 | * the post body to be transparently re-sent if the HTTP request must be
30 | * sent multiple times.
31 | */
32 | public final class RetryableSink implements Sink {
33 | private boolean closed;
34 | private final int limit;
35 | private final Buffer content = new Buffer();
36 |
37 | public RetryableSink(int limit) {
38 | this.limit = limit;
39 | }
40 |
41 | public RetryableSink() {
42 | this(-1);
43 | }
44 |
45 | @Override public void close() throws IOException {
46 | if (closed) return;
47 | closed = true;
48 | if (content.size() < limit) {
49 | throw new ProtocolException(
50 | "content-length promised " + limit + " bytes, but received " + content.size());
51 | }
52 | }
53 |
54 | @Override public void write(Buffer source, long byteCount) throws IOException {
55 | if (closed) throw new IllegalStateException("closed");
56 | checkOffsetAndCount(source.size(), 0, byteCount);
57 | if (limit != -1 && content.size() > limit - byteCount) {
58 | throw new ProtocolException("exceeded content-length limit of " + limit + " bytes");
59 | }
60 | content.write(source, byteCount);
61 | }
62 |
63 | @Override public void flush() throws IOException {
64 | }
65 |
66 | @Override public Timeout timeout() {
67 | return Timeout.NONE;
68 | }
69 |
70 | public long contentLength() throws IOException {
71 | return content.size();
72 | }
73 |
74 | public void writeToSocket(Sink socketOut) throws IOException {
75 | // Copy the content; otherwise we won't have data to retry.
76 | Buffer buffer = new Buffer();
77 | content.copyTo(buffer, 0, content.size());
78 | socketOut.write(buffer, buffer.size());
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/internal/http/RouteException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package okhttp3.internal.http;
17 |
18 | import java.io.IOException;
19 | import java.lang.reflect.InvocationTargetException;
20 | import java.lang.reflect.Method;
21 |
22 | /**
23 | * An exception thrown to indicate a problem connecting via a single Route. Multiple attempts may
24 | * have been made with alternative protocols, none of which were successful.
25 | */
26 | public final class RouteException extends Exception {
27 | private static final Method addSuppressedExceptionMethod;
28 | static {
29 | Method m;
30 | try {
31 | m = Throwable.class.getDeclaredMethod("addSuppressed", Throwable.class);
32 | } catch (Exception e) {
33 | m = null;
34 | }
35 | addSuppressedExceptionMethod = m;
36 | }
37 | private IOException lastException;
38 |
39 | public RouteException(IOException cause) {
40 | super(cause);
41 | lastException = cause;
42 | }
43 |
44 | public IOException getLastConnectException() {
45 | return lastException;
46 | }
47 |
48 | public void addConnectException(IOException e) {
49 | addSuppressedIfPossible(e, lastException);
50 | lastException = e;
51 | }
52 |
53 | private void addSuppressedIfPossible(IOException e, IOException suppressed) {
54 | if (addSuppressedExceptionMethod != null) {
55 | try {
56 | addSuppressedExceptionMethod.invoke(e, suppressed);
57 | } catch (InvocationTargetException | IllegalAccessException ignored) {
58 | }
59 | }
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/internal/http/StatusLine.java:
--------------------------------------------------------------------------------
1 | package okhttp3.internal.http;
2 |
3 | import okhttp3.Protocol;
4 | import okhttp3.Response;
5 | import java.io.IOException;
6 | import java.net.ProtocolException;
7 |
8 | /** An HTTP response status line like "HTTP/1.1 200 OK". */
9 | public final class StatusLine {
10 | /** Numeric status code, 307: Temporary Redirect. */
11 | public static final int HTTP_TEMP_REDIRECT = 307;
12 | public static final int HTTP_PERM_REDIRECT = 308;
13 | public static final int HTTP_CONTINUE = 100;
14 |
15 | public final Protocol protocol;
16 | public final int code;
17 | public final String message;
18 |
19 | public StatusLine(Protocol protocol, int code, String message) {
20 | this.protocol = protocol;
21 | this.code = code;
22 | this.message = message;
23 | }
24 |
25 | public static StatusLine get(Response response) {
26 | return new StatusLine(response.protocol(), response.code(), response.message());
27 | }
28 |
29 | public static StatusLine parse(String statusLine) throws IOException {
30 | // H T T P / 1 . 1 2 0 0 T e m p o r a r y R e d i r e c t
31 | // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
32 |
33 | // Parse protocol like "HTTP/1.1" followed by a space.
34 | int codeStart;
35 | Protocol protocol;
36 | if (statusLine.startsWith("HTTP/1.")) {
37 | if (statusLine.length() < 9 || statusLine.charAt(8) != ' ') {
38 | throw new ProtocolException("Unexpected status line: " + statusLine);
39 | }
40 | int httpMinorVersion = statusLine.charAt(7) - '0';
41 | codeStart = 9;
42 | if (httpMinorVersion == 0) {
43 | protocol = Protocol.HTTP_1_0;
44 | } else if (httpMinorVersion == 1) {
45 | protocol = Protocol.HTTP_1_1;
46 | } else {
47 | throw new ProtocolException("Unexpected status line: " + statusLine);
48 | }
49 | } else if (statusLine.startsWith("ICY ")) {
50 | // Shoutcast uses ICY instead of "HTTP/1.0".
51 | protocol = Protocol.HTTP_1_0;
52 | codeStart = 4;
53 | } else {
54 | throw new ProtocolException("Unexpected status line: " + statusLine);
55 | }
56 |
57 | // Parse response code like "200". Always 3 digits.
58 | if (statusLine.length() < codeStart + 3) {
59 | throw new ProtocolException("Unexpected status line: " + statusLine);
60 | }
61 | int code;
62 | try {
63 | code = Integer.parseInt(statusLine.substring(codeStart, codeStart + 3));
64 | } catch (NumberFormatException e) {
65 | throw new ProtocolException("Unexpected status line: " + statusLine);
66 | }
67 |
68 | // Parse an optional response message like "OK" or "Not Modified". If it
69 | // exists, it is separated from the response code by a space.
70 | String message = "";
71 | if (statusLine.length() > codeStart + 3) {
72 | if (statusLine.charAt(codeStart + 3) != ' ') {
73 | throw new ProtocolException("Unexpected status line: " + statusLine);
74 | }
75 | message = statusLine.substring(codeStart + 4);
76 | }
77 |
78 | return new StatusLine(protocol, code, message);
79 | }
80 |
81 | @Override public String toString() {
82 | StringBuilder result = new StringBuilder();
83 | result.append(protocol == Protocol.HTTP_1_0 ? "HTTP/1.0" : "HTTP/1.1");
84 | result.append(' ').append(code);
85 | if (message != null) {
86 | result.append(' ').append(message);
87 | }
88 | return result.toString();
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/okio/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/okio/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'java'
2 |
3 |
4 | allprojects {
5 | tasks.withType(Javadoc) {
6 | options.encoding = "UTF-8"
7 | }
8 | }
9 | dependencies {
10 | // compile 'org.codehaus.mojo:animal-sniffer-annotations:1.14'
11 | }
--------------------------------------------------------------------------------
/okio/src/main/java/okio/ForwardingSink.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2014 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package okio;
17 |
18 | import java.io.IOException;
19 |
20 | /** A {@link Sink} which forwards calls to another. Useful for subclassing. */
21 | public abstract class ForwardingSink implements Sink {
22 | private final Sink delegate;
23 |
24 | public ForwardingSink(Sink delegate) {
25 | if (delegate == null) throw new IllegalArgumentException("delegate == null");
26 | this.delegate = delegate;
27 | }
28 |
29 | /** {@link Sink} to which this instance is delegating. */
30 | public final Sink delegate() {
31 | return delegate;
32 | }
33 |
34 | @Override public void write(Buffer source, long byteCount) throws IOException {
35 | delegate.write(source, byteCount);
36 | }
37 |
38 | @Override public void flush() throws IOException {
39 | delegate.flush();
40 | }
41 |
42 | @Override public Timeout timeout() {
43 | return delegate.timeout();
44 | }
45 |
46 | @Override public void close() throws IOException {
47 | delegate.close();
48 | }
49 |
50 | @Override public String toString() {
51 | return getClass().getSimpleName() + "(" + delegate.toString() + ")";
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/okio/src/main/java/okio/ForwardingSource.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2014 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package okio;
17 |
18 | import java.io.IOException;
19 |
20 | /** A {@link Source} which forwards calls to another. Useful for subclassing. */
21 | public abstract class ForwardingSource implements Source {
22 | private final Source delegate;
23 |
24 | public ForwardingSource(Source delegate) {
25 | if (delegate == null) throw new IllegalArgumentException("delegate == null");
26 | this.delegate = delegate;
27 | }
28 |
29 | /** {@link Source} to which this instance is delegating. */
30 | public final Source delegate() {
31 | return delegate;
32 | }
33 |
34 | @Override public long read(Buffer sink, long byteCount) throws IOException {
35 | return delegate.read(sink, byteCount);
36 | }
37 |
38 | @Override public Timeout timeout() {
39 | return delegate.timeout();
40 | }
41 |
42 | @Override public void close() throws IOException {
43 | delegate.close();
44 | }
45 |
46 | @Override public String toString() {
47 | return getClass().getSimpleName() + "(" + delegate.toString() + ")";
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/okio/src/main/java/okio/ForwardingTimeout.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package okio;
17 |
18 | import java.io.IOException;
19 | import java.util.concurrent.TimeUnit;
20 |
21 | /** A {@link Timeout} which forwards calls to another. Useful for subclassing. */
22 | public class ForwardingTimeout extends Timeout {
23 | private Timeout delegate;
24 |
25 | public ForwardingTimeout(Timeout delegate) {
26 | if (delegate == null) throw new IllegalArgumentException("delegate == null");
27 | this.delegate = delegate;
28 | }
29 |
30 | /** {@link Timeout} instance to which this instance is currently delegating. */
31 | public final Timeout delegate() {
32 | return delegate;
33 | }
34 |
35 | public final ForwardingTimeout setDelegate(Timeout delegate) {
36 | if (delegate == null) throw new IllegalArgumentException("delegate == null");
37 | this.delegate = delegate;
38 | return this;
39 | }
40 |
41 | @Override public Timeout timeout(long timeout, TimeUnit unit) {
42 | return delegate.timeout(timeout, unit);
43 | }
44 |
45 | @Override public long timeoutNanos() {
46 | return delegate.timeoutNanos();
47 | }
48 |
49 | @Override public boolean hasDeadline() {
50 | return delegate.hasDeadline();
51 | }
52 |
53 | @Override public long deadlineNanoTime() {
54 | return delegate.deadlineNanoTime();
55 | }
56 |
57 | @Override public Timeout deadlineNanoTime(long deadlineNanoTime) {
58 | return delegate.deadlineNanoTime(deadlineNanoTime);
59 | }
60 |
61 | @Override public Timeout clearTimeout() {
62 | return delegate.clearTimeout();
63 | }
64 |
65 | @Override public Timeout clearDeadline() {
66 | return delegate.clearDeadline();
67 | }
68 |
69 | @Override public void throwIfReached() throws IOException {
70 | delegate.throwIfReached();
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/okio/src/main/java/okio/SegmentPool.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2014 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package okio;
17 |
18 | /**
19 | * A collection of unused segments, necessary to avoid GC churn and zero-fill.
20 | * This pool is a thread-safe static singleton.
21 | */
22 | final class SegmentPool {
23 | /** The maximum number of bytes to pool. */
24 | // TODO: Is 64 KiB a good maximum size? Do we ever have that many idle segments?
25 | static final long MAX_SIZE = 64 * 1024; // 64 KiB.
26 |
27 | /** Singly-linked list of segments. */
28 | static Segment next;
29 |
30 | /** Total bytes in this pool. */
31 | static long byteCount;
32 |
33 | private SegmentPool() {
34 | }
35 |
36 | static Segment take() {
37 | synchronized (SegmentPool.class) {
38 | if (next != null) {
39 | Segment result = next;
40 | next = result.next;
41 | result.next = null;
42 | byteCount -= Segment.SIZE;
43 | return result;
44 | }
45 | }
46 | return new Segment(); // Pool is empty. Don't zero-fill while holding a lock.
47 | }
48 |
49 | static void recycle(Segment segment) {
50 | if (segment.next != null || segment.prev != null) throw new IllegalArgumentException();
51 | if (segment.shared) return; // This segment cannot be recycled.
52 | synchronized (SegmentPool.class) {
53 | if (byteCount + Segment.SIZE > MAX_SIZE) return; // Pool is full.
54 | byteCount += Segment.SIZE;
55 | segment.next = next;
56 | segment.pos = segment.limit = 0;
57 | next = segment;
58 | }
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/okio/src/main/java/okio/Sink.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2014 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package okio;
17 |
18 | import java.io.Closeable;
19 | import java.io.Flushable;
20 | import java.io.IOException;
21 |
22 | /**
23 | * Receives a stream of bytes. Use this interface to write data wherever it's
24 | * needed: to the network, storage, or a buffer in memory. Sinks may be layered
25 | * to transform received data, such as to compress, encrypt, throttle, or add
26 | * protocol framing.
27 | *
28 | *
Most application code shouldn't operate on a sink directly, but rather on a
29 | * {@link BufferedSink} which is both more efficient and more convenient. Use
30 | * {@link Okio#buffer(Sink)} to wrap any sink with a buffer.
31 | *
32 | *
Sinks are easy to test: just use a {@link Buffer} in your tests, and
33 | * read from it to confirm it received the data that was expected.
34 | *
35 | *
Comparison with OutputStream
36 | * This interface is functionally equivalent to {@link java.io.OutputStream}.
37 | *
38 | *
{@code OutputStream} requires multiple layers when emitted data is
39 | * heterogeneous: a {@code DataOutputStream} for primitive values, a {@code
40 | * BufferedOutputStream} for buffering, and {@code OutputStreamWriter} for
41 | * charset encoding. This class uses {@code BufferedSink} for all of the above.
42 | *
43 | *
Sink is also easier to layer: there is no {@linkplain
44 | * java.io.OutputStream#write(int) single-byte write} method that is awkward to
45 | * implement efficiently.
46 | *
47 | *
Interop with OutputStream
48 | * Use {@link Okio#sink} to adapt an {@code OutputStream} to a sink. Use {@link
49 | * BufferedSink#outputStream} to adapt a sink to an {@code OutputStream}.
50 | */
51 | public interface Sink extends Closeable, Flushable {
52 | /** Removes {@code byteCount} bytes from {@code source} and appends them to this. */
53 | void write(Buffer source, long byteCount) throws IOException;
54 |
55 | /** Pushes all buffered bytes to their final destination. */
56 | @Override void flush() throws IOException;
57 |
58 | /** Returns the timeout for this sink. */
59 | Timeout timeout();
60 |
61 | /**
62 | * Pushes all buffered bytes to their final destination and releases the
63 | * resources held by this sink. It is an error to write a closed sink. It is
64 | * safe to close a sink more than once.
65 | */
66 | @Override void close() throws IOException;
67 | }
68 |
--------------------------------------------------------------------------------
/okio/src/main/java/okio/Source.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2014 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package okio;
17 |
18 | import java.io.Closeable;
19 | import java.io.IOException;
20 |
21 | /**
22 | * Supplies a stream of bytes. Use this interface to read data from wherever
23 | * it's located: from the network, storage, or a buffer in memory. Sources may
24 | * be layered to transform supplied data, such as to decompress, decrypt, or
25 | * remove protocol framing.
26 | *
27 | *
Most applications shouldn't operate on a source directly, but rather on a
28 | * {@link BufferedSource} which is both more efficient and more convenient. Use
29 | * {@link Okio#buffer(Source)} to wrap any source with a buffer.
30 | *
31 | *
Sources are easy to test: just use a {@link Buffer} in your tests, and
32 | * fill it with the data your application is to read.
33 | *
34 | *
Comparison with InputStream
35 | * This interface is functionally equivalent to {@link java.io.InputStream}.
36 | *
37 | *
{@code InputStream} requires multiple layers when consumed data is
38 | * heterogeneous: a {@code DataInputStream} for primitive values, a {@code
39 | * BufferedInputStream} for buffering, and {@code InputStreamReader} for
40 | * strings. This class uses {@code BufferedSource} for all of the above.
41 | *
42 | *
Source avoids the impossible-to-implement {@linkplain
43 | * java.io.InputStream#available available()} method. Instead callers specify
44 | * how many bytes they {@link BufferedSource#require require}.
45 | *
46 | *
Source omits the unsafe-to-compose {@linkplain java.io.InputStream#mark
47 | * mark and reset} state that's tracked by {@code InputStream}; instead, callers
48 | * just buffer what they need.
49 | *
50 | *
When implementing a source, you don't need to worry about the {@linkplain
51 | * java.io.InputStream#read single-byte read} method that is awkward to implement efficiently
52 | * and returns one of 257 possible values.
53 | *
54 | *
And source has a stronger {@code skip} method: {@link BufferedSource#skip}
55 | * won't return prematurely.
56 | *
57 | *
Interop with InputStream
58 | * Use {@link Okio#source} to adapt an {@code InputStream} to a source. Use
59 | * {@link BufferedSource#inputStream} to adapt a source to an {@code
60 | * InputStream}.
61 | */
62 | public interface Source extends Closeable {
63 | /**
64 | * Removes at least 1, and up to {@code byteCount} bytes from this and appends
65 | * them to {@code sink}. Returns the number of bytes read, or -1 if this
66 | * source is exhausted.
67 | */
68 | long read(Buffer sink, long byteCount) throws IOException;
69 |
70 | /** Returns the timeout for this source. */
71 | Timeout timeout();
72 |
73 | /**
74 | * Closes this source and releases the resources held by this source. It is an
75 | * error to read a closed source. It is safe to close a source more than once.
76 | */
77 | @Override void close() throws IOException;
78 | }
79 |
--------------------------------------------------------------------------------
/okio/src/main/java/okio/Util.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2014 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package okio;
17 |
18 | import java.nio.charset.Charset;
19 |
20 | final class Util {
21 | /** A cheap and type-safe constant for the UTF-8 Charset. */
22 | public static final Charset UTF_8 = Charset.forName("UTF-8");
23 |
24 | private Util() {
25 | }
26 |
27 | public static void checkOffsetAndCount(long size, long offset, long byteCount) {
28 | if ((offset | byteCount) < 0 || offset > size || size - offset < byteCount) {
29 | throw new ArrayIndexOutOfBoundsException(
30 | String.format("size=%s offset=%s byteCount=%s", size, offset, byteCount));
31 | }
32 | }
33 |
34 | public static short reverseBytesShort(short s) {
35 | int i = s & 0xffff;
36 | int reversed = (i & 0xff00) >>> 8
37 | | (i & 0x00ff) << 8;
38 | return (short) reversed;
39 | }
40 |
41 | public static int reverseBytesInt(int i) {
42 | return (i & 0xff000000) >>> 24
43 | | (i & 0x00ff0000) >>> 8
44 | | (i & 0x0000ff00) << 8
45 | | (i & 0x000000ff) << 24;
46 | }
47 |
48 | public static long reverseBytesLong(long v) {
49 | return (v & 0xff00000000000000L) >>> 56
50 | | (v & 0x00ff000000000000L) >>> 40
51 | | (v & 0x0000ff0000000000L) >>> 24
52 | | (v & 0x000000ff00000000L) >>> 8
53 | | (v & 0x00000000ff000000L) << 8
54 | | (v & 0x0000000000ff0000L) << 24
55 | | (v & 0x000000000000ff00L) << 40
56 | | (v & 0x00000000000000ffL) << 56;
57 | }
58 |
59 | /**
60 | * Throws {@code t}, even if the declared throws clause doesn't permit it.
61 | * This is a terrible but terribly convenient hack that makes it easy to
62 | * catch and rethrow exceptions after cleanup. See Java Puzzlers #43.
63 | */
64 | public static void sneakyRethrow(Throwable t) {
65 | Util.sneakyThrow2(t);
66 | }
67 |
68 | @SuppressWarnings("unchecked")
69 | private static void sneakyThrow2(Throwable t) throws T {
70 | throw (T) t;
71 | }
72 |
73 | public static boolean arrayRangeEquals(
74 | byte[] a, int aOffset, byte[] b, int bOffset, int byteCount) {
75 | for (int i = 0; i < byteCount; i++) {
76 | if (a[i + aOffset] != b[i + bOffset]) return false;
77 | }
78 | return true;
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':okhttp', ':okio', ':app', ':library'
2 |
--------------------------------------------------------------------------------