HttpRequest.Builder builder = new HttpRequest.Builder(); 7 | *
builder.url(url); 8 | *
addHeaders(builder, headers); 9 | *
//网络请求返回的默认类型就是string,如下载文件和加载图片需要用到InputStream,则设置为ResponseType.InputStream 10 | *
builder.setResponseType(ResponseType.InputStream); 11 | *
mHttpBase.get(builder.build(), listener, tag);
12 | */
13 | public enum ResponseType {
14 | String("String"), InputStream("InputStream");
15 | private final String type;
16 |
17 | ResponseType(String type) {
18 | this.type = type;
19 | }
20 |
21 | @Override
22 | public String toString() {
23 | return type;
24 | }
25 | }
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in E:\BaiduYunDownload\adt-bundle-windows-x86_64-20140702\adt-bundle-windows-x86_64-20140702\sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/library/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in E:\BaiduYunDownload\adt-bundle-windows-x86_64-20140702\adt-bundle-windows-x86_64-20140702\sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 | 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/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 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 Typical implementations will look up a credential and create a request
32 | * derived from the initial request by setting the "Authorization" header.
33 | * Typical implementations will look up a credential and create a request
50 | * derived from the initial request by setting the "Proxy-Authorization"
51 | * header. 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/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 While {@link #onReset} may occur at any time, the following callbacks are
29 | * expected in order, correlated by stream ID.
30 | * 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 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 | * 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/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/MediaType.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.nio.charset.Charset;
19 | import java.util.Locale;
20 | import java.util.regex.Matcher;
21 | import java.util.regex.Pattern;
22 |
23 | /**
24 | * An RFC 2045 Media Type,
25 | * appropriate to describe the content type of an HTTP request or response body.
26 | */
27 | public final class MediaType {
28 | private static final String TOKEN = "([a-zA-Z0-9-!#$%&'*+.^_`{|}~]+)";
29 | private static final String QUOTED = "\"([^\"]*)\"";
30 | private static final Pattern TYPE_SUBTYPE = Pattern.compile(TOKEN + "/" + TOKEN);
31 | private static final Pattern PARAMETER = Pattern.compile(
32 | ";\\s*(?:" + TOKEN + "=(?:" + TOKEN + "|" + QUOTED + "))?");
33 |
34 | private final String mediaType;
35 | private final String type;
36 | private final String subtype;
37 | private final String charset;
38 |
39 | private MediaType(String mediaType, String type, String subtype, String charset) {
40 | this.mediaType = mediaType;
41 | this.type = type;
42 | this.subtype = subtype;
43 | this.charset = charset;
44 | }
45 |
46 | /**
47 | * Returns a media type for {@code string}, or null if {@code string} is not a
48 | * well-formed media type.
49 | */
50 | public static MediaType parse(String string) {
51 | Matcher typeSubtype = TYPE_SUBTYPE.matcher(string);
52 | if (!typeSubtype.lookingAt()) return null;
53 | String type = typeSubtype.group(1).toLowerCase(Locale.US);
54 | String subtype = typeSubtype.group(2).toLowerCase(Locale.US);
55 |
56 | String charset = null;
57 | Matcher parameter = PARAMETER.matcher(string);
58 | for (int s = typeSubtype.end(); s < string.length(); s = parameter.end()) {
59 | parameter.region(s, string.length());
60 | if (!parameter.lookingAt()) return null; // This is not a well-formed media type.
61 |
62 | String name = parameter.group(1);
63 | if (name == null || !name.equalsIgnoreCase("charset")) continue;
64 | String charsetParameter = parameter.group(2) != null
65 | ? parameter.group(2) // Value is a token.
66 | : parameter.group(3); // Value is a quoted string.
67 | if (charset != null && !charsetParameter.equalsIgnoreCase(charset)) {
68 | throw new IllegalArgumentException("Multiple different charsets: " + string);
69 | }
70 | charset = charsetParameter;
71 | }
72 |
73 | return new MediaType(string, type, subtype, charset);
74 | }
75 |
76 | /**
77 | * Returns the high-level media type, such as "text", "image", "audio",
78 | * "video", or "application".
79 | */
80 | public String type() {
81 | return type;
82 | }
83 |
84 | /**
85 | * Returns a specific media subtype, such as "plain" or "png", "mpeg",
86 | * "mp4" or "xml".
87 | */
88 | public String subtype() {
89 | return subtype;
90 | }
91 |
92 | /**
93 | * Returns the charset of this media type, or null if this media type doesn't
94 | * specify a charset.
95 | */
96 | public Charset charset() {
97 | return charset != null ? Charset.forName(charset) : null;
98 | }
99 |
100 | /**
101 | * Returns the charset of this media type, or {@code defaultValue} if this
102 | * media type doesn't specify a charset.
103 | */
104 | public Charset charset(Charset defaultValue) {
105 | return charset != null ? Charset.forName(charset) : defaultValue;
106 | }
107 |
108 | /**
109 | * Returns the encoded media type, like "text/plain; charset=utf-8",
110 | * appropriate for use in a Content-Type header.
111 | */
112 | @Override public String toString() {
113 | return mediaType;
114 | }
115 |
116 | @Override public boolean equals(Object o) {
117 | return o instanceof MediaType && ((MediaType) o).mediaType.equals(mediaType);
118 | }
119 |
120 | @Override public int hashCode() {
121 | return mediaType.hashCode();
122 | }
123 | }
124 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/internal/framed/FrameWriter.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.framed;
18 |
19 | import java.io.Closeable;
20 | import java.io.IOException;
21 | import java.util.List;
22 | import okio.Buffer;
23 |
24 | /** Writes transport frames for SPDY/3 or HTTP/2. */
25 | public interface FrameWriter extends Closeable {
26 | /** HTTP/2 only. */
27 | void connectionPreface() throws IOException;
28 | /** Informs the peer that we've applied its latest settings. */
29 | void ackSettings(Settings peerSettings) throws IOException;
30 |
31 | /**
32 | * HTTP/2 only. Send a push promise header block.
33 | *
34 | * A push promise contains all the headers that pertain to a server-initiated
35 | * request, and a {@code promisedStreamId} to which response frames will be
36 | * delivered. Push promise frames are sent as a part of the response to
37 | * {@code streamId}. The {@code promisedStreamId} has a priority of one
38 | * greater than {@code streamId}.
39 | *
40 | * @param streamId client-initiated stream ID. Must be an odd number.
41 | * @param promisedStreamId server-initiated stream ID. Must be an even
42 | * number.
43 | * @param requestHeaders minimally includes {@code :method}, {@code :scheme},
44 | * {@code :authority}, and (@code :path}.
45 | */
46 | void pushPromise(int streamId, int promisedStreamId, List
78 | * In SPDY/3, only the first {@code payload1} parameter is sent. If the
79 | * sender is a client, it is an unsigned odd number. Likewise, a server
80 | * will send an even number.
81 | *
82 | * In HTTP/2, both {@code payload1} and {@code payload2} parameters are
83 | * sent. The data is opaque binary, and there are no rules on the content.
84 | */
85 | void ping(boolean ack, int payload1, int payload2) throws IOException;
86 |
87 | /**
88 | * Tell the peer to stop creating streams and that we last processed
89 | * {@code lastGoodStreamId}, or zero if no streams were processed.
90 | *
91 | * @param lastGoodStreamId the last stream ID processed, or zero if no
92 | * streams were processed.
93 | * @param errorCode reason for closing the connection.
94 | * @param debugData only valid for HTTP/2; opaque debug data to send.
95 | */
96 | void goAway(int lastGoodStreamId, ErrorCode errorCode, byte[] debugData) throws IOException;
97 |
98 | /**
99 | * Inform peer that an additional {@code windowSizeIncrement} bytes can be
100 | * sent on {@code streamId}, or the connection if {@code streamId} is zero.
101 | */
102 | void windowUpdate(int streamId, long windowSizeIncrement) throws IOException;
103 | }
104 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/internal/framed/NameValueBlockReader.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 java.io.IOException;
19 | import java.util.ArrayList;
20 | import java.util.List;
21 | import java.util.zip.DataFormatException;
22 | import java.util.zip.Inflater;
23 | import okio.Buffer;
24 | import okio.BufferedSource;
25 | import okio.ByteString;
26 | import okio.ForwardingSource;
27 | import okio.InflaterSource;
28 | import okio.Okio;
29 | import okio.Source;
30 |
31 | /**
32 | * Reads a SPDY/3 Name/Value header block. This class is made complicated by the
33 | * requirement that we're strict with which bytes we put in the compressed bytes
34 | * buffer. We need to put all compressed bytes into that buffer -- but no other
35 | * bytes.
36 | */
37 | class NameValueBlockReader {
38 | /** This source transforms compressed bytes into uncompressed bytes. */
39 | private final InflaterSource inflaterSource;
40 |
41 | /**
42 | * How many compressed bytes must be read into inflaterSource before
43 | * {@link #readNameValueBlock} returns.
44 | */
45 | private int compressedLimit;
46 |
47 | /** This source holds inflated bytes. */
48 | private final BufferedSource source;
49 |
50 | public NameValueBlockReader(BufferedSource source) {
51 | // Limit the inflater input stream to only those bytes in the Name/Value
52 | // block. We cut the inflater off at its source because we can't predict the
53 | // ratio of compressed bytes to uncompressed bytes.
54 | Source throttleSource = new ForwardingSource(source) {
55 | @Override public long read(Buffer sink, long byteCount) throws IOException {
56 | if (compressedLimit == 0) return -1; // Out of data for the current block.
57 | long read = super.read(sink, Math.min(byteCount, compressedLimit));
58 | if (read == -1) return -1;
59 | compressedLimit -= read;
60 | return read;
61 | }
62 | };
63 |
64 | // Subclass inflater to install a dictionary when it's needed.
65 | Inflater inflater = new Inflater() {
66 | @Override public int inflate(byte[] buffer, int offset, int count)
67 | throws DataFormatException {
68 | int result = super.inflate(buffer, offset, count);
69 | if (result == 0 && needsDictionary()) {
70 | setDictionary(Spdy3.DICTIONARY);
71 | result = super.inflate(buffer, offset, count);
72 | }
73 | return result;
74 | }
75 | };
76 |
77 | this.inflaterSource = new InflaterSource(throttleSource, inflater);
78 | this.source = Okio.buffer(inflaterSource);
79 | }
80 |
81 | public List This value object describes a completed handshake. Use {@link
33 | * javax.net.ssl.SSLSocketFactory} to set policy for new handshakes.
34 | */
35 | public final class Handshake {
36 | private final CipherSuite cipherSuite;
37 | private final List All operations on a file system are racy. For example, guarding a call to {@link #source}
32 | * with {@link #exists} does not guarantee that {@link FileNotFoundException} will not be thrown.
33 | * The file may be moved between the two calls!
34 | *
35 | * This interface is less ambitious than {@link java.nio.file.FileSystem} introduced in Java 7.
36 | * It lacks important features like file watching, metadata, permissions, and disk space
37 | * information. In exchange for these limitations, this interface is easier to implement and works
38 | * on all versions of Java and Android.
39 | */
40 | public interface FileSystem {
41 | /** The host machine's local file system. */
42 | FileSystem SYSTEM = new FileSystem() {
43 | @Override public Source source(File file) throws FileNotFoundException {
44 | return Okio.source(file);
45 | }
46 |
47 | @Override public Sink sink(File file) throws FileNotFoundException {
48 | try {
49 | return Okio.sink(file);
50 | } catch (FileNotFoundException e) {
51 | // Maybe the parent directory doesn't exist? Try creating it first.
52 | file.getParentFile().mkdirs();
53 | return Okio.sink(file);
54 | }
55 | }
56 |
57 | @Override public Sink appendingSink(File file) throws FileNotFoundException {
58 | try {
59 | return Okio.appendingSink(file);
60 | } catch (FileNotFoundException e) {
61 | // Maybe the parent directory doesn't exist? Try creating it first.
62 | file.getParentFile().mkdirs();
63 | return Okio.appendingSink(file);
64 | }
65 | }
66 |
67 | @Override public void delete(File file) throws IOException {
68 | // If delete() fails, make sure it's because the file didn't exist!
69 | if (!file.delete() && file.exists()) {
70 | throw new IOException("failed to delete " + file);
71 | }
72 | }
73 |
74 | @Override public boolean exists(File file) throws IOException {
75 | return file.exists();
76 | }
77 |
78 | @Override public long size(File file) {
79 | return file.length();
80 | }
81 |
82 | @Override public void rename(File from, File to) throws IOException {
83 | delete(to);
84 | if (!from.renameTo(to)) {
85 | throw new IOException("failed to rename " + from + " to " + to);
86 | }
87 | }
88 |
89 | @Override public void deleteContents(File directory) throws IOException {
90 | File[] files = directory.listFiles();
91 | if (files == null) {
92 | throw new IOException("not a readable directory: " + directory);
93 | }
94 | for (File file : files) {
95 | if (file.isDirectory()) {
96 | deleteContents(file);
97 | }
98 | if (!file.delete()) {
99 | throw new IOException("failed to delete " + file);
100 | }
101 | }
102 | }
103 | };
104 |
105 | /** Reads from {@code file}. */
106 | Source source(File file) throws FileNotFoundException;
107 |
108 | /**
109 | * Writes to {@code file}, discarding any data already present. Creates parent directories if
110 | * necessary.
111 | */
112 | Sink sink(File file) throws FileNotFoundException;
113 |
114 | /**
115 | * Writes to {@code file}, appending if data is already present. Creates parent directories if
116 | * necessary.
117 | */
118 | Sink appendingSink(File file) throws FileNotFoundException;
119 |
120 | /** Deletes {@code file} if it exists. Throws if the file exists and cannot be deleted. */
121 | void delete(File file) throws IOException;
122 |
123 | /** Returns true if {@code file} exists on the file system. */
124 | boolean exists(File file) throws IOException;
125 |
126 | /** Returns the number of bytes stored in {@code file}, or 0 if it does not exist. */
127 | long size(File file);
128 |
129 | /** Renames {@code from} to {@code to}. Throws if the file cannot be renamed. */
130 | void rename(File from, File to) throws IOException;
131 |
132 | /**
133 | * Recursively delete the contents of {@code directory}. Throws an IOException if any file could
134 | * not be deleted, or if {@code dir} is not a readable directory.
135 | */
136 | void deleteContents(File directory) throws IOException;
137 | }
138 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/internal/ConnectionSpecSelector.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 |
17 | package okhttp3.internal;
18 |
19 | import okhttp3.ConnectionSpec;
20 | import java.io.IOException;
21 | import java.io.InterruptedIOException;
22 | import java.net.ProtocolException;
23 | import java.net.UnknownServiceException;
24 | import java.security.cert.CertificateException;
25 | import java.util.Arrays;
26 | import java.util.List;
27 | import javax.net.ssl.SSLHandshakeException;
28 | import javax.net.ssl.SSLPeerUnverifiedException;
29 | import javax.net.ssl.SSLProtocolException;
30 | import javax.net.ssl.SSLSocket;
31 |
32 | /**
33 | * Handles the connection spec fallback strategy: When a secure socket connection fails
34 | * due to a handshake / protocol problem the connection may be retried with different protocols.
35 | * Instances are stateful and should be created and used for a single connection attempt.
36 | */
37 | public final class ConnectionSpecSelector {
38 |
39 | private final List {@code
34 | *
35 | * String credential = Credentials.basic(...)
36 | * return response.request().newBuilder()
37 | * .header("Authorization", credential)
38 | * .build();
39 | * }
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 | * {@code
52 | *
53 | * String credential = Credentials.basic(...)
54 | * return response.request().newBuilder()
55 | * .header("Proxy-Authorization", credential)
56 | * .build();
57 | * }
58 | */
59 | Request authenticateProxy(Proxy proxy, Response response) throws IOException;
60 | }
61 |
--------------------------------------------------------------------------------
/app/src/main/java/com/huxq17/example/http/request/CountingRequestBody.java:
--------------------------------------------------------------------------------
1 | package com.huxq17.example.http.request;
2 |
3 | import com.andbase.tractor.task.Task;
4 |
5 | import java.io.IOException;
6 |
7 | import okhttp3.MediaType;
8 | import okhttp3.RequestBody;
9 | import okio.Buffer;
10 | import okio.BufferedSink;
11 | import okio.ForwardingSink;
12 | import okio.Okio;
13 | import okio.Sink;
14 |
15 | /**
16 | * Decorates an OkHttp request body to count the number of bytes written when writing it. Can
17 | * decorate any request body, but is most useful for tracking the upload progress of large
18 | * multipart requests.
19 | *
20 | * @author Leo Nikkil
21 | */
22 | public class CountingRequestBody extends RequestBody {
23 |
24 | protected RequestBody delegate;
25 | protected Task mTask;
26 | private int mProcess = -1;
27 |
28 | protected CountingSink countingSink;
29 |
30 | public CountingRequestBody(RequestBody delegate, Task task) {
31 | this.delegate = delegate;
32 | this.mTask = task;
33 | }
34 |
35 | @Override
36 | public MediaType contentType() {
37 | return delegate.contentType();
38 | }
39 |
40 | @Override
41 | public long contentLength() {
42 | try {
43 | return delegate.contentLength();
44 | } catch (IOException e) {
45 | e.printStackTrace();
46 | }
47 | return -1;
48 | }
49 |
50 | @Override
51 | public void writeTo(BufferedSink sink) throws IOException {
52 | BufferedSink bufferedSink;
53 |
54 | countingSink = new CountingSink(sink);
55 | bufferedSink = Okio.buffer(countingSink);
56 |
57 | delegate.writeTo(bufferedSink);
58 |
59 | bufferedSink.flush();
60 | }
61 |
62 | protected final class CountingSink extends ForwardingSink {
63 |
64 | private long bytesWritten = 0;
65 |
66 | public CountingSink(Sink delegate) {
67 | super(delegate);
68 | }
69 |
70 | @Override
71 | public void write(Buffer source, long byteCount) throws IOException {
72 | super.write(source, byteCount);
73 |
74 | bytesWritten += byteCount;
75 | int process = (int) (1.0 * bytesWritten / contentLength() * 100);
76 | if (mTask != null&&process!=mProcess) {
77 | mTask.notifyLoading(process);
78 | mProcess = process;
79 | }
80 | if (process == 100) {
81 | mTask = null;
82 | }
83 | }
84 |
85 | }
86 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/huxq17/example/http/body/FileBody.java:
--------------------------------------------------------------------------------
1 | package com.huxq17.example.http.body;
2 |
3 | import java.io.File;
4 | import java.net.FileNameMap;
5 | import java.net.URLConnection;
6 |
7 | /**
8 | * Created by huxq17 on 2015/11/26.
9 | */
10 | public class FileBody {
11 | /* 上传文件的数据 */
12 | private byte[] data;
13 | private File file;
14 | /* 文件路径 */
15 | private String filePath;
16 | /* 请求参数名称*/
17 | private String parameterName;
18 | /* 内容类型 */
19 | private String contentType = "application/octet-stream";
20 |
21 | public FileBody(String parameterName, byte[] data, String filePath, String contentType) {
22 | this.data = data;
23 | this.filePath = filePath;
24 | this.parameterName = parameterName;
25 | if (contentType != null) {
26 | this.contentType = contentType;
27 | } else {
28 | this.contentType = getContentType(filePath);
29 | }
30 | }
31 |
32 | private String getContentType(String path) {
33 | FileNameMap fileNameMap = URLConnection.getFileNameMap();
34 | String contentType = fileNameMap.getContentTypeFor(path);
35 | if (contentType == null) {
36 | contentType = "application/octet-stream";
37 | }
38 | return contentType;
39 | }
40 |
41 | public FileBody(String parameterName, String filePath, File file) {
42 | this(parameterName,filePath,file,null);
43 | }
44 |
45 | public FileBody(String parameterName, String filePath, File file, String contentType) {
46 | this.filePath = filePath;
47 | this.parameterName = parameterName;
48 | this.file = file;
49 | if (contentType != null) {
50 | this.contentType = contentType;
51 | } else {
52 | this.contentType = getContentType(filePath);
53 | }
54 | }
55 |
56 | public File getFile() {
57 | return file;
58 | }
59 |
60 | public byte[] getData() {
61 | return data;
62 | }
63 |
64 | public String getFilPath() {
65 | return filePath;
66 | }
67 |
68 | public void setFilePath(String filePath) {
69 | this.filePath = filePath;
70 | }
71 |
72 | public String getParameterName() {
73 | return parameterName;
74 | }
75 |
76 | public void setParameterName(String parameterName) {
77 | this.parameterName = parameterName;
78 | }
79 |
80 | public String getContentType() {
81 | return contentType;
82 | }
83 |
84 | public void setContentType(String contentType) {
85 | this.contentType = contentType;
86 | }
87 |
88 | }
89 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/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/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/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/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 |
--------------------------------------------------------------------------------
/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 | *
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/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 | *
31 | *
35 | *
36 | * 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 | *
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 | *