├── okcurl
├── src
│ └── main
│ │ └── resources
│ │ └── okcurl-version.properties
└── README.md
├── website
└── static
│ ├── icon-github.png
│ ├── icon-square.png
│ ├── logo-square.png
│ ├── app-theme.css
│ ├── jquery-maven-artifact.min.js
│ ├── html5shiv.min.js
│ └── jquery.smooth-scroll.min.js
├── .gitmodules
├── .gitignore
├── .buildscript
├── settings.xml
└── deploy_snapshot.sh
├── benchmarks
├── README.md
└── src
│ └── main
│ └── java
│ └── okhttp3
│ └── benchmarks
│ ├── HttpClient.java
│ ├── Client.java
│ └── SynchronousHttpClient.java
├── okhttp-ws-tests
├── fuzzingserver-update-expected.sh
├── fuzzingserver-test.sh
└── pom.xml
├── okhttp-apache
├── README.md
├── src
│ └── main
│ │ └── java
│ │ └── okhttp3
│ │ └── apache
│ │ └── HttpEntityBody.java
└── pom.xml
├── BUG-BOUNTY.md
├── okhttp-hpacktests
├── README.md
├── src
│ └── test
│ │ └── java
│ │ └── okhttp3
│ │ └── internal
│ │ └── spdy
│ │ ├── HpackDecodeInteropTest.java
│ │ ├── hpackjson
│ │ ├── Story.java
│ │ └── Case.java
│ │ └── HpackRoundTripTest.java
└── pom.xml
├── .travis.yml
├── okhttp-ws
├── README.md
├── pom.xml
└── src
│ └── main
│ └── java
│ └── okhttp3
│ └── ws
│ └── WebSocket.java
├── okhttp
├── src
│ └── main
│ │ ├── java
│ │ └── okhttp3
│ │ │ ├── AsycCallComparator.java
│ │ │ ├── internal
│ │ │ ├── http
│ │ │ │ ├── CacheRequest.java
│ │ │ │ ├── RequestException.java
│ │ │ │ ├── RealResponseBody.java
│ │ │ │ ├── RequestLine.java
│ │ │ │ ├── HttpMethod.java
│ │ │ │ ├── RouteException.java
│ │ │ │ ├── HeaderParser.java
│ │ │ │ ├── HttpStream.java
│ │ │ │ └── RetryableSink.java
│ │ │ ├── FaultHidingSink.java
│ │ │ ├── NamedRunnable.java
│ │ │ ├── framed
│ │ │ │ ├── Variant.java
│ │ │ │ ├── HeadersMode.java
│ │ │ │ ├── Header.java
│ │ │ │ ├── Ping.java
│ │ │ │ └── ErrorCode.java
│ │ │ ├── RouteDatabase.java
│ │ │ └── InternalCache.java
│ │ │ ├── Interceptor.java
│ │ │ ├── Credentials.java
│ │ │ ├── TlsVersion.java
│ │ │ ├── Callback.java
│ │ │ ├── Challenge.java
│ │ │ ├── Dns.java
│ │ │ ├── Authenticator.java
│ │ │ └── CookieJar.java
│ │ └── java-templates
│ │ └── okhttp3
│ │ └── internal
│ │ └── Version.java
└── pom.xml
├── CONTRIBUTING.md
├── samples
├── guide
│ ├── src
│ │ └── main
│ │ │ └── java
│ │ │ └── okhttp3
│ │ │ ├── guide
│ │ │ ├── GetExample.java
│ │ │ ├── PostExample.java
│ │ │ └── PriorityExample.java
│ │ │ └── recipes
│ │ │ ├── PostForm.java
│ │ │ ├── ConfigureTimeouts.java
│ │ │ ├── SynchronousGet.java
│ │ │ ├── PostFile.java
│ │ │ ├── AccessHeaders.java
│ │ │ ├── PostString.java
│ │ │ ├── ParseResponseWithGson.java
│ │ │ ├── AsynchronousGet.java
│ │ │ ├── CertificatePinning.java
│ │ │ ├── Authenticate.java
│ │ │ ├── PerCallSettings.java
│ │ │ ├── LoggingInterceptors.java
│ │ │ ├── CheckHandshake.java
│ │ │ ├── PostStreaming.java
│ │ │ ├── PostMultipart.java
│ │ │ ├── CancelCall.java
│ │ │ ├── CacheResponse.java
│ │ │ └── WebSocketEcho.java
│ └── pom.xml
├── pom.xml
├── simple-client
│ ├── pom.xml
│ └── src
│ │ └── main
│ │ └── java
│ │ └── okhttp3
│ │ └── sample
│ │ └── OkHttpContributors.java
├── crawler
│ └── pom.xml
└── static-server
│ └── pom.xml
├── deploy_website.sh
├── okhttp-android-support
├── src
│ ├── main
│ │ └── java
│ │ │ └── okhttp3
│ │ │ ├── OkCacheContainer.java
│ │ │ └── AndroidInternal.java
│ └── test
│ │ └── java
│ │ └── okhttp3
│ │ └── AbstractResponseCache.java
└── pom.xml
├── okhttp-tests
├── src
│ └── test
│ │ └── java
│ │ └── okhttp3
│ │ ├── internal
│ │ ├── framed
│ │ │ ├── HttpOverSpdy3Test.java
│ │ │ ├── HuffmanTest.java
│ │ │ └── BaseTestHandler.java
│ │ ├── DoubleInetAddressDns.java
│ │ ├── SingleInetAddressDns.java
│ │ ├── http
│ │ │ ├── RecordingProxySelector.java
│ │ │ ├── RouteExceptionTest.java
│ │ │ ├── FakeDns.java
│ │ │ ├── ExternalHttp2Example.java
│ │ │ └── ExternalSpdyExample.java
│ │ ├── RecordingAuthenticator.java
│ │ └── RecordingOkAuthenticator.java
│ │ ├── TestLogHandler.java
│ │ ├── TestUtil.java
│ │ ├── AddressTest.java
│ │ ├── DelegatingServerSocketFactory.java
│ │ ├── FallbackTestClientSocketFactory.java
│ │ ├── RecordingCallback.java
│ │ └── DelegatingSocketFactory.java
└── pom.xml
├── okhttp-testing-support
├── pom.xml
└── src
│ └── main
│ └── java
│ └── okhttp3
│ ├── testing
│ └── RecordingHostnameVerifier.java
│ └── RecordingCookieJar.java
├── okhttp-logging-interceptor
├── pom.xml
└── README.md
├── mockwebserver
├── src
│ └── main
│ │ └── java
│ │ └── okhttp3
│ │ └── mockwebserver
│ │ ├── PushPromise.java
│ │ ├── Dispatcher.java
│ │ └── QueueDispatcher.java
└── pom.xml
├── okhttp-urlconnection
├── pom.xml
└── src
│ └── main
│ └── java
│ └── okhttp3
│ └── internal
│ └── JavaNetHeaders.java
└── README.md
/okcurl/src/main/resources/okcurl-version.properties:
--------------------------------------------------------------------------------
1 | version=${project.version}
2 |
--------------------------------------------------------------------------------
/website/static/icon-github.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lizhangqu/PriorityOkHttp/HEAD/website/static/icon-github.png
--------------------------------------------------------------------------------
/website/static/icon-square.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lizhangqu/PriorityOkHttp/HEAD/website/static/icon-square.png
--------------------------------------------------------------------------------
/website/static/logo-square.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lizhangqu/PriorityOkHttp/HEAD/website/static/logo-square.png
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "okhttp-hpacktests/src/test/resources/hpack-test-case"]
2 | path = okhttp-hpacktests/src/test/resources/hpack-test-case
3 | url = git://github.com/http2jp/hpack-test-case.git
4 |
--------------------------------------------------------------------------------
/okcurl/README.md:
--------------------------------------------------------------------------------
1 | OkCurl
2 | ======
3 |
4 | _A curl for the next-generation web._
5 |
6 | OkCurl is an OkHttp-backed curl clone which allows you to test OkHttp's HTTP engine (including
7 | SPDY and HTTP/2) against web servers.
8 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .classpath
2 | .project
3 | .settings
4 | eclipsebin
5 |
6 | bin
7 | gen
8 | build
9 | out
10 | lib
11 |
12 | target
13 | pom.xml.*
14 | release.properties
15 |
16 | .idea
17 | *.iml
18 | *.ipr
19 | *.iws
20 | classes
21 |
22 | obj
23 |
24 | .DS_Store
25 |
--------------------------------------------------------------------------------
/.buildscript/settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | sonatype-nexus-snapshots
5 | ${env.CI_DEPLOY_USERNAME}
6 | ${env.CI_DEPLOY_PASSWORD}
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/benchmarks/README.md:
--------------------------------------------------------------------------------
1 | OkHttp Benchmarks
2 | =======================================
3 |
4 | This module allows you to test the performance of HTTP clients.
5 |
6 | ### Running
7 | 1. If you made modifications to `Benchmark` run `mvn compile`.
8 | 2. Run `mvn exec:exec` to launch a new JVM, which will execute the benchmark.
9 |
--------------------------------------------------------------------------------
/okhttp-ws-tests/fuzzingserver-update-expected.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | SCRIPT_DIR="$( cd "$( dirname "$0" )" && pwd )"
4 | cd "$SCRIPT_DIR"
5 |
6 | if [ ! -f target/fuzzingserver-actual.txt ]; then
7 | echo "File not found. Did you run the Autobahn test script?"
8 | exit 1
9 | fi
10 |
11 | cp target/fuzzingserver-actual.txt fuzzingserver-expected.txt
12 |
--------------------------------------------------------------------------------
/okhttp-apache/README.md:
--------------------------------------------------------------------------------
1 | OkHttp Apache HttpClient Implementation
2 | =======================================
3 |
4 | This module is an implementation of the Apache `HttpClient` interface that is backed by OkHttp.
5 |
6 | **Warning**: Many core features of Apache HTTP client are not implemented by this API. This includes
7 | the keep-alive strategy, cookie store, credentials provider, route planner and others.
8 |
--------------------------------------------------------------------------------
/BUG-BOUNTY.md:
--------------------------------------------------------------------------------
1 | Serious about security
2 | ======================
3 |
4 | Square recognizes the important contributions the security research community
5 | can make. We therefore encourage reporting security issues with the code
6 | contained in this repository.
7 |
8 | If you believe you have discovered a security vulnerability, please follow the
9 | guidelines at https://hackerone.com/square-open-source
10 |
11 |
--------------------------------------------------------------------------------
/okhttp-hpacktests/README.md:
--------------------------------------------------------------------------------
1 | OkHttp HPACK tests
2 | ==================
3 |
4 | These tests use the [hpack-test-case][1] project to validate OkHttp's HPACK
5 | implementation. The HPACK test cases are in a separate git submodule, so to
6 | initialize them, you must run:
7 |
8 | git submodule init
9 | git submodule update
10 |
11 | TODO
12 | ----
13 |
14 | * Add maven goal to avoid manual call to git submodule init.
15 | * Make hpack-test-case update itself from git, and run new tests.
16 | * Add maven goal to generate stories and a pull request to hpack-test-case
17 | to have others validate our output.
18 |
19 | [1]: https://github.com/http2jp/hpack-test-case
20 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: java
2 |
3 | jdk:
4 | - oraclejdk7
5 | - oraclejdk8
6 |
7 | after_success:
8 | - .buildscript/deploy_snapshot.sh
9 |
10 | env:
11 | global:
12 | - secure: "S0BTJVrF4fUCwhTdmoQY6LYr5r1wgXZ/p8lc5bIgUUsc1Ckalwt7s/GDwPuLJ4702sI5t56Eye2iEIMUjeFJKqebZRsX1C5oYsYFxGi3BGlepstYpmj0gLXuSWqCLniS9zmHXCxLhLkC6KxPVjhDlbq76XQx0o3K1J8oEIj/PCE="
13 | - secure: "awV7yLXURjlPbTOladsNDZk74KYCNXoiZpAP0gQFfK4Sc0fc7+kg8z/yhdWXeTxjsIZ6m0dVDHTqnH8ytnydwXpBam8JdQJ+EAWA6R3Svq1BR1bzl/PcZUoz+Xn8lMXdU3yA1p4qtQlUhMxwsE3MOVe24HSDJPAu4XeWFj1j3qo="
14 |
15 | branches:
16 | except:
17 | - gh-pages
18 |
19 | notifications:
20 | email: false
21 |
22 | sudo: false
23 |
24 | cache:
25 | directories:
26 | - $HOME/.m2
27 |
--------------------------------------------------------------------------------
/okhttp-ws/README.md:
--------------------------------------------------------------------------------
1 | OkHttp Web Sockets
2 | ==================
3 |
4 | RFC6455-compliant web socket implementation.
5 |
6 | Create a `WebSocketCall` with a `Request` and an `OkHttpClient` instance.
7 | ```java
8 | WebSocketCall call = WebSocketCall.create(client, request);
9 | ```
10 |
11 | A `WebSocketListener` will notify of the initial connection, server-sent messages, and any failures
12 | on the connection.
13 |
14 | Start the web socket by calling `enqueue` on `WebSocketCall` with the `WebSocketListener`.
15 | ```java
16 | call.enqueue(new WebSocketListener() {
17 | // ...
18 | });
19 | ```
20 |
21 | *Note: This module's API should be considered experimental and may be subject to breaking changes
22 | in future releases.*
23 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/AsycCallComparator.java:
--------------------------------------------------------------------------------
1 | package okhttp3;
2 |
3 | import java.util.Comparator;
4 |
5 | /**
6 | * Created by lizhangqu on 16/1/17.
7 | */
8 | public class AsycCallComparator implements Comparator {
9 |
10 | @Override
11 | public int compare(T object1, T object2) {
12 |
13 | if ((object1 instanceof RealCall.AsyncCall)
14 | && (object2 instanceof RealCall.AsyncCall)) {
15 |
16 | RealCall.AsyncCall task1 = (RealCall.AsyncCall) object1;
17 | RealCall.AsyncCall task2 = (RealCall.AsyncCall) object2;
18 |
19 | int result = task2.priority()
20 | - task1.priority();
21 |
22 | return result;
23 | }
24 | return 0;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | Contributing
2 | ============
3 |
4 | If you would like to contribute code to OkHttp you can do so through GitHub by
5 | forking the repository and sending a pull request.
6 |
7 | When submitting code, please make every effort to follow existing conventions
8 | and style in order to keep the code as readable as possible. Please also make
9 | sure your code compiles by running `mvn clean verify`. Checkstyle failures
10 | during compilation indicate errors in your style and can be viewed in the
11 | `checkstyle-result.xml` file.
12 |
13 | Before your code can be accepted into the project you must also sign the
14 | [Individual Contributor License Agreement (CLA)][1].
15 |
16 |
17 | [1]: https://spreadsheets.google.com/spreadsheet/viewform?formkey=dDViT2xzUHAwRkI3X3k5Z0lQM091OGc6MQ&ndplr=1
18 |
--------------------------------------------------------------------------------
/samples/guide/src/main/java/okhttp3/guide/GetExample.java:
--------------------------------------------------------------------------------
1 | package okhttp3.guide;
2 |
3 | import java.io.IOException;
4 | import okhttp3.OkHttpClient;
5 | import okhttp3.Request;
6 | import okhttp3.Response;
7 |
8 | public class GetExample {
9 | OkHttpClient client = new OkHttpClient();
10 |
11 | String run(String url) throws IOException {
12 | Request request = new Request.Builder()
13 | .url(url)
14 | .build();
15 |
16 | Response response = client.newCall(request).execute();
17 | return response.body().string();
18 | }
19 |
20 | public static void main(String[] args) throws IOException {
21 | GetExample example = new GetExample();
22 | String response = example.run("https://raw.github.com/square/okhttp/master/README.md");
23 | System.out.println(response);
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/okhttp-ws-tests/fuzzingserver-test.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | SCRIPT_DIR="$( cd "$( dirname "$0" )" && pwd )"
4 | cd "$SCRIPT_DIR"
5 |
6 | which wstest
7 | if [ $? != 0 ]; then
8 | echo "Run 'pip install autobahntestsuite', maybe with 'sudo'."
9 | exit 1
10 | fi
11 | which jq
12 | if [ $? != 0 ]; then
13 | echo "Run 'brew install jq'"
14 | exit 1
15 | fi
16 |
17 | trap 'kill $(jobs -pr)' SIGINT SIGTERM EXIT
18 |
19 | set -ex
20 |
21 | wstest -m fuzzingserver -s fuzzingserver-config.json &
22 | sleep 2 # wait for wstest to start
23 |
24 | java -jar target/okhttp-ws-tests-*-jar-with-dependencies.jar
25 |
26 | jq '.[] as $in | $in | keys[] | . + " " + $in[.].behavior' target/fuzzingserver-report/index.json > target/fuzzingserver-actual.txt
27 |
28 | diff fuzzingserver-expected.txt target/fuzzingserver-actual.txt
29 |
--------------------------------------------------------------------------------
/samples/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 4.0.0
5 |
6 |
7 | com.squareup.okhttp3
8 | parent
9 | 3.1.0-SNAPSHOT
10 |
11 |
12 | com.squareup.okhttp3.sample
13 | sample-parent
14 | pom
15 | Samples (Parent)
16 |
17 |
18 | guide
19 | crawler
20 | simple-client
21 | static-server
22 |
23 |
24 |
--------------------------------------------------------------------------------
/deploy_website.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | set -ex
4 |
5 | REPO="git@github.com:square/okhttp.git"
6 | DIR=temp-clone
7 |
8 | # Delete any existing temporary website clone
9 | rm -rf $DIR
10 |
11 | # Clone the current repo into temp folder
12 | git clone $REPO $DIR
13 |
14 | # Move working directory into temp folder
15 | cd $DIR
16 |
17 | # Checkout and track the gh-pages branch
18 | git checkout -t origin/gh-pages
19 |
20 | # Delete everything that isn't versioned (1.x, 2.x)
21 | ls | grep -E -v '^\d+\.x$' | xargs rm -rf
22 |
23 | # Copy website files from real repo
24 | cp -R ../website/* .
25 |
26 | # Stage all files in git and create a commit
27 | git add .
28 | git add -u
29 | git commit -m "Website at $(date)"
30 |
31 | # Push the new files up to GitHub
32 | git push origin gh-pages
33 |
34 | # Delete our temp folder
35 | cd ..
36 | rm -rf $DIR
37 |
--------------------------------------------------------------------------------
/okhttp/src/main/java-templates/okhttp3/internal/Version.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 | public final class Version {
19 | public static String userAgent() {
20 | return "okhttp/${project.version}";
21 | }
22 |
23 | private Version() {
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/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 |
24 | void abort();
25 | }
26 |
--------------------------------------------------------------------------------
/okhttp-android-support/src/main/java/okhttp3/OkCacheContainer.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 | /**
19 | * An interface that allows OkHttp to detect that a {@link java.net.ResponseCache} contains a {@link
20 | * Cache}.
21 | */
22 | public interface OkCacheContainer {
23 | Cache getCache();
24 | }
25 |
--------------------------------------------------------------------------------
/okhttp-tests/src/test/java/okhttp3/internal/framed/HttpOverSpdy3Test.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 |
20 | public class HttpOverSpdy3Test extends HttpOverSpdyTest {
21 |
22 | public HttpOverSpdy3Test() {
23 | super(Protocol.SPDY_3);
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/samples/simple-client/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 4.0.0
5 |
6 |
7 | com.squareup.okhttp3.sample
8 | sample-parent
9 | 3.1.0-SNAPSHOT
10 |
11 |
12 | simple-client
13 | Sample: Simple Client
14 |
15 |
16 |
17 | com.squareup.okhttp3
18 | okhttp
19 | ${project.version}
20 |
21 |
22 |
23 | com.google.code.gson
24 | gson
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/samples/crawler/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 4.0.0
5 |
6 |
7 | com.squareup.okhttp3.sample
8 | sample-parent
9 | 3.1.0-SNAPSHOT
10 |
11 |
12 | crawler
13 | Sample: Crawler
14 |
15 |
16 |
17 | com.squareup.okhttp3
18 | okhttp
19 | ${project.version}
20 |
21 |
22 | org.jsoup
23 | jsoup
24 | 1.7.3
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/benchmarks/src/main/java/okhttp3/benchmarks/HttpClient.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.benchmarks;
17 |
18 | import okhttp3.HttpUrl;
19 |
20 | /** An HTTP client to benchmark. */
21 | interface HttpClient {
22 | void prepare(Benchmark benchmark);
23 |
24 | void enqueue(HttpUrl url) throws Exception;
25 |
26 | boolean acceptingJobs();
27 | }
28 |
--------------------------------------------------------------------------------
/okhttp-testing-support/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 4.0.0
5 |
6 |
7 | com.squareup.okhttp3
8 | parent
9 | 3.1.0-SNAPSHOT
10 |
11 |
12 | okhttp-testing-support
13 | OkHttp test support classes
14 |
15 |
16 |
17 | junit
18 | junit
19 | true
20 |
21 |
22 | ${project.groupId}
23 | okhttp
24 | ${project.version}
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/.buildscript/deploy_snapshot.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | #
3 | # Deploy a jar, source jar, and javadoc jar to Sonatype's snapshot repo.
4 | #
5 | # Adapted from https://coderwall.com/p/9b_lfq and
6 | # http://benlimmer.com/2013/12/26/automatically-publish-javadoc-to-gh-pages-with-travis-ci/
7 |
8 | SLUG="square/okhttp"
9 | JDK="oraclejdk8"
10 | BRANCH="master"
11 |
12 | set -e
13 |
14 | if [ "$TRAVIS_REPO_SLUG" != "$SLUG" ]; then
15 | echo "Skipping snapshot deployment: wrong repository. Expected '$SLUG' but was '$TRAVIS_REPO_SLUG'."
16 | elif [ "$TRAVIS_JDK_VERSION" != "$JDK" ]; then
17 | echo "Skipping snapshot deployment: wrong JDK. Expected '$JDK' but was '$TRAVIS_JDK_VERSION'."
18 | elif [ "$TRAVIS_PULL_REQUEST" != "false" ]; then
19 | echo "Skipping snapshot deployment: was pull request."
20 | elif [ "$TRAVIS_BRANCH" != "$BRANCH" ]; then
21 | echo "Skipping snapshot deployment: wrong branch. Expected '$BRANCH' but was '$TRAVIS_BRANCH'."
22 | else
23 | echo "Deploying snapshot..."
24 | mvn clean source:jar javadoc:jar deploy --settings=".buildscript/settings.xml" -Dmaven.test.skip=true
25 | echo "Snapshot deployed!"
26 | fi
27 |
--------------------------------------------------------------------------------
/samples/guide/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 4.0.0
5 |
6 |
7 | com.squareup.okhttp3.sample
8 | sample-parent
9 | 3.1.0-SNAPSHOT
10 |
11 |
12 | guide
13 | Sample: Guide
14 |
15 |
16 |
17 | com.squareup.okhttp3
18 | okhttp
19 | ${project.version}
20 |
21 |
22 | com.squareup.okhttp3
23 | okhttp-ws
24 | ${project.version}
25 |
26 |
27 | com.google.code.gson
28 | gson
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/okhttp-testing-support/src/main/java/okhttp3/testing/RecordingHostnameVerifier.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2013 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 | package okhttp3.testing;
17 |
18 | import java.util.ArrayList;
19 | import java.util.List;
20 | import javax.net.ssl.HostnameVerifier;
21 | import javax.net.ssl.SSLSession;
22 |
23 | public final class RecordingHostnameVerifier implements HostnameVerifier {
24 | public final List calls = new ArrayList<>();
25 |
26 | public boolean verify(String hostname, SSLSession session) {
27 | calls.add("verify " + hostname);
28 | return true;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/website/static/app-theme.css:
--------------------------------------------------------------------------------
1 | /* http://www.colorhexa.com/487fb9 */
2 |
3 | /*** Primary ***/
4 |
5 | header,
6 | #subtitle,
7 | a.dl {
8 | background-color: #48b7b9;
9 | }
10 |
11 | .content-nav li.active a,
12 | .content-nav li.active a:hover {
13 | border-left-color: #48b7b9;
14 | }
15 |
16 | /*** One step left on the monochromatic scale ***/
17 |
18 | header menu li a:hover,
19 | a.dl:hover {
20 | background-color: #40a6a7;
21 | }
22 | a {
23 | color: #40a6a7;
24 | }
25 |
26 | /*** Three steps left on the monochromatic scale ***/
27 |
28 | a:hover {
29 | color: #328183;
30 | }
31 |
32 |
33 | /****************************************************************\
34 | **** Syntax highlighting styles ********************************
35 | \****************************************************************/
36 |
37 | .pln { color: #000; }
38 | .str { color: #399395; }
39 | .kwd { color: #666; }
40 | .com { color: #399395; }
41 | .typ { color: #222; }
42 | .lit { color: #666; }
43 | .pun { color: #888; }
44 | .opn { color: #888; }
45 | .clo { color: #888; }
46 | .tag { color: #399395; }
47 | .atn { color: #606; }
48 | .atv { color: #080; }
49 | .dec { color: #606; }
50 | .var { color: #606; }
51 | .fun { color: #f00; }
52 |
--------------------------------------------------------------------------------
/okhttp-ws/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 4.0.0
5 |
6 |
7 | com.squareup.okhttp3
8 | parent
9 | 3.1.0-SNAPSHOT
10 |
11 |
12 | okhttp-ws
13 | OkHttp Web Sockets
14 |
15 |
16 |
17 | ${project.groupId}
18 | okhttp
19 | ${project.version}
20 |
21 |
22 |
23 |
24 |
25 |
26 | org.apache.maven.plugins
27 | maven-javadoc-plugin
28 |
29 | okhttp3.internal.*
30 |
31 | http://square.github.io/okhttp/javadoc/
32 |
33 |
34 |
35 |
36 |
37 |
38 |
--------------------------------------------------------------------------------
/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/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 |
31 | Response proceed(Request request) throws IOException;
32 |
33 | Connection connection();
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/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/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-tests/src/test/java/okhttp3/internal/DoubleInetAddressDns.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 java.net.InetAddress;
19 | import java.net.UnknownHostException;
20 | import java.util.Arrays;
21 | import java.util.List;
22 | import okhttp3.Dns;
23 |
24 | /**
25 | * A network that always resolves two IP addresses per host. Use this when testing route selection
26 | * fallbacks to guarantee that a fallback address is available.
27 | */
28 | public class DoubleInetAddressDns implements Dns {
29 | @Override public List lookup(String hostname) throws UnknownHostException {
30 | List addresses = Dns.SYSTEM.lookup(hostname);
31 | return Arrays.asList(addresses.get(0), addresses.get(0));
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/benchmarks/src/main/java/okhttp3/benchmarks/Client.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.benchmarks;
17 |
18 | enum Client {
19 | OkHttp {
20 | @Override HttpClient create() {
21 | return new OkHttp();
22 | }
23 | },
24 |
25 | OkHttpAsync {
26 | @Override HttpClient create() {
27 | return new OkHttpAsync();
28 | }
29 | },
30 |
31 | Apache {
32 | @Override HttpClient create() {
33 | return new ApacheHttpClient();
34 | }
35 | },
36 |
37 | UrlConnection {
38 | @Override HttpClient create() {
39 | return new UrlConnection();
40 | }
41 | },
42 |
43 | Netty {
44 | @Override HttpClient create() {
45 | return new NettyHttpClient();
46 | }
47 | };
48 |
49 | abstract HttpClient create();
50 | }
51 |
--------------------------------------------------------------------------------
/okhttp-tests/src/test/java/okhttp3/internal/SingleInetAddressDns.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 java.net.InetAddress;
19 | import java.net.UnknownHostException;
20 | import java.util.Collections;
21 | import java.util.List;
22 | import okhttp3.Dns;
23 |
24 | /**
25 | * A network that resolves only one IP address per host. Use this when testing route selection
26 | * fallbacks to prevent the host machine's various IP addresses from interfering.
27 | */
28 | public class SingleInetAddressDns implements Dns {
29 | @Override public List lookup(String hostname) throws UnknownHostException {
30 | List addresses = Dns.SYSTEM.lookup(hostname);
31 | return Collections.singletonList(addresses.get(0));
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/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-logging-interceptor/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 4.0.0
5 |
6 |
7 | com.squareup.okhttp3
8 | parent
9 | 3.1.0-SNAPSHOT
10 |
11 |
12 | logging-interceptor
13 | OkHttp Logging Interceptor
14 |
15 |
16 |
17 | ${project.groupId}
18 | okhttp
19 | ${project.version}
20 |
21 |
22 |
23 | junit
24 | junit
25 | test
26 |
27 |
28 | ${project.groupId}
29 | mockwebserver
30 | ${project.version}
31 | test
32 |
33 |
34 | ${project.groupId}
35 | okhttp-testing-support
36 | ${project.version}
37 | test
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/okhttp-apache/src/main/java/okhttp3/apache/HttpEntityBody.java:
--------------------------------------------------------------------------------
1 | package okhttp3.apache;
2 |
3 | import java.io.IOException;
4 | import okhttp3.MediaType;
5 | import okhttp3.RequestBody;
6 | import okio.BufferedSink;
7 | import org.apache.http.HttpEntity;
8 |
9 | /** Adapts an {@link HttpEntity} to OkHttp's {@link RequestBody}. */
10 | final class HttpEntityBody extends RequestBody {
11 | private static final MediaType DEFAULT_MEDIA_TYPE = MediaType.parse("application/octet-stream");
12 |
13 | private final HttpEntity entity;
14 | private final MediaType mediaType;
15 |
16 | HttpEntityBody(HttpEntity entity, String contentTypeHeader) {
17 | this.entity = entity;
18 |
19 | if (contentTypeHeader != null) {
20 | mediaType = MediaType.parse(contentTypeHeader);
21 | } else if (entity.getContentType() != null) {
22 | mediaType = MediaType.parse(entity.getContentType().getValue());
23 | } else {
24 | // Apache is forgiving and lets you skip specifying a content type with an entity. OkHttp is
25 | // not forgiving so we fall back to a generic type if it's missing.
26 | mediaType = DEFAULT_MEDIA_TYPE;
27 | }
28 | }
29 |
30 | @Override public long contentLength() {
31 | return entity.getContentLength();
32 | }
33 |
34 | @Override public MediaType contentType() {
35 | return mediaType;
36 | }
37 |
38 | @Override public void writeTo(BufferedSink sink) throws IOException {
39 | entity.writeTo(sink.outputStream());
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/website/static/jquery-maven-artifact.min.js:
--------------------------------------------------------------------------------
1 | /**
2 | * jQuery Maven Artifact Plugin
3 | *
4 | * Version: 2.0.0
5 | * Author: Jake Wharton
6 | * License: Apache 2.0
7 | */(function(e){function n(e,t){var n=e.groupId.replace(/\./g,"/"),r="http://repo1.maven.org/maven2/"+n+"/"+e.artifactId+"/"+t+"/"+e.artifactId+"-"+t;return typeof e.classifier!="undefined"&&(r+="-"+e.classifier),r+="."+e.packaging,r}function r(e){var t={groupId:"g",artifactId:"a",packaging:"p",classifier:"l"},n="";for(var r in t)t.hasOwnProperty(r)&&e.hasOwnProperty(r)&&(n!==""&&(n+="+AND+"),n+=t[r]+':"'+e[r]+'"');return n}var t={packaging:"jar"};e.fn.artifactVersion=function(i,s){if(typeof i=="undefined"){alert("Error: config object is required.");return}if(typeof s=="undefined"){alert("Error: callback function required.");return}var i=e.extend({},t,i),o="http://search.maven.org/solrsearch/select/?q="+r(i)+"&wt=json&json.wrf=?";e.getJSON(o,function(e){var t=e.response.docs;if(t.length==0)return;var r=t[0].latestVersion||t[0].v,o=n(i,r);s(r,o)})},e.fn.artifactVersions=function(i,s){if(typeof i=="undefined"){alert("Error: config object is required.");return}if(typeof s=="undefined"){alert("Error: callback function required.");return}var i=e.extend({},t,i),o="http://search.maven.org/solrsearch/select/?q="+r(i)+"&wt=json&rows=10&core=gav&json.wrf=?";e.getJSON(o,function(e){var t=e.response.docs;if(t.length==0)return;t.sort(function(e,t){return e.v>t.v?-1:1});var r=[];for(var o=0;o
37 | com.squareup.okhttp3
38 | logging-interceptor
39 | (insert latest version)
40 |
41 | ```
42 |
43 | or via Gradle
44 | ```groovy
45 | compile 'com.squareup.okhttp3:logging-interceptor:(insert latest version)'
46 | ```
47 |
48 |
49 |
50 | [1]: https://github.com/square/okhttp/wiki/Interceptors
51 |
--------------------------------------------------------------------------------
/okhttp-hpacktests/src/test/java/okhttp3/internal/spdy/HpackDecodeInteropTest.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.spdy;
17 |
18 | import java.util.Collection;
19 | import okhttp3.internal.spdy.hpackjson.Story;
20 | import org.junit.Test;
21 | import org.junit.runner.RunWith;
22 | import org.junit.runners.Parameterized;
23 |
24 | import static okhttp3.internal.spdy.hpackjson.HpackJsonUtil.storiesForCurrentDraft;
25 |
26 | @RunWith(Parameterized.class)
27 | public class HpackDecodeInteropTest extends HpackDecodeTestBase {
28 |
29 | public HpackDecodeInteropTest(Story story) {
30 | super(story);
31 | }
32 |
33 | @Parameterized.Parameters(name = "{0}")
34 | public static Collection createStories() throws Exception {
35 | return createStories(storiesForCurrentDraft());
36 | }
37 |
38 | @Test
39 | public void testGoodDecoderInterop() throws Exception {
40 | testDecoder();
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/mockwebserver/src/main/java/okhttp3/mockwebserver/Dispatcher.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2012 Google 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.mockwebserver;
17 |
18 | /** Handler for mock server requests. */
19 | public abstract class Dispatcher {
20 | /**
21 | * Returns a response to satisfy {@code request}. This method may block (for instance, to wait on
22 | * a CountdownLatch).
23 | */
24 | public abstract MockResponse dispatch(RecordedRequest request) throws InterruptedException;
25 |
26 | /**
27 | * Returns an early guess of the next response, used for policy on how an incoming request should
28 | * be received. The default implementation returns an empty response. Mischievous implementations
29 | * can return other values to test HTTP edge cases, such as unhappy socket policies or throttled
30 | * request bodies.
31 | */
32 | public MockResponse peek() {
33 | return new MockResponse().setSocketPolicy(SocketPolicy.KEEP_OPEN);
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/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-tests/src/test/java/okhttp3/TestLogHandler.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.util.ArrayList;
19 | import java.util.List;
20 | import java.util.logging.Handler;
21 | import java.util.logging.LogRecord;
22 |
23 | /**
24 | * A log handler that records which log messages were published so that a calling test can make
25 | * assertions about them.
26 | */
27 | public final class TestLogHandler extends Handler {
28 | private final List logs = new ArrayList<>();
29 |
30 | @Override public synchronized void publish(LogRecord logRecord) {
31 | logs.add(logRecord.getLevel() + ": " + logRecord.getMessage());
32 | notifyAll();
33 | }
34 |
35 | @Override public void flush() {
36 | }
37 |
38 | @Override public void close() throws SecurityException {
39 | }
40 |
41 | public synchronized String take() throws InterruptedException {
42 | while (logs.isEmpty()) {
43 | wait();
44 | }
45 | return logs.remove(0);
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/samples/guide/src/main/java/okhttp3/guide/PostExample.java:
--------------------------------------------------------------------------------
1 | package okhttp3.guide;
2 |
3 | import java.io.IOException;
4 | import okhttp3.MediaType;
5 | import okhttp3.OkHttpClient;
6 | import okhttp3.Request;
7 | import okhttp3.RequestBody;
8 | import okhttp3.Response;
9 |
10 | public class PostExample {
11 | public static final MediaType JSON
12 | = MediaType.parse("application/json; charset=utf-8");
13 |
14 | OkHttpClient client = new OkHttpClient();
15 |
16 | String post(String url, String json) throws IOException {
17 | RequestBody body = RequestBody.create(JSON, json);
18 | Request request = new Request.Builder()
19 | .url(url)
20 | .post(body)
21 | .build();
22 | Response response = client.newCall(request).execute();
23 | return response.body().string();
24 | }
25 |
26 | String bowlingJson(String player1, String player2) {
27 | return "{'winCondition':'HIGH_SCORE',"
28 | + "'name':'Bowling',"
29 | + "'round':4,"
30 | + "'lastSaved':1367702411696,"
31 | + "'dateStarted':1367702378785,"
32 | + "'players':["
33 | + "{'name':'" + player1 + "','history':[10,8,6,7,8],'color':-13388315,'total':39},"
34 | + "{'name':'" + player2 + "','history':[6,10,5,10,10],'color':-48060,'total':41}"
35 | + "]}";
36 | }
37 |
38 | public static void main(String[] args) throws IOException {
39 | PostExample example = new PostExample();
40 | String json = example.bowlingJson("Jesse", "Jake");
41 | String response = example.post("http://www.roundsapp.com/post", json);
42 | System.out.println(response);
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/okhttp-android-support/src/test/java/okhttp3/AbstractResponseCache.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 | import java.net.CacheRequest;
20 | import java.net.CacheResponse;
21 | import java.net.ResponseCache;
22 | import java.net.URI;
23 | import java.net.URISyntaxException;
24 | import java.net.URL;
25 | import java.net.URLConnection;
26 | import java.util.List;
27 | import java.util.Map;
28 |
29 | public class AbstractResponseCache extends ResponseCache {
30 | @Override public CacheResponse get(URI uri, String requestMethod,
31 | Map> requestHeaders) throws IOException {
32 | return null;
33 | }
34 |
35 | @Override public CacheRequest put(URI uri, URLConnection connection) throws IOException {
36 | return null;
37 | }
38 |
39 | public static URI toUri(URL serverUrl) {
40 | try {
41 | return serverUrl.toURI();
42 | } catch (URISyntaxException e) {
43 | throw new AssertionError(e);
44 | }
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/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 | /**
19 | * Versions of TLS that can be offered when negotiating a secure socket. See {@link
20 | * javax.net.ssl.SSLSocket#setEnabledProtocols}.
21 | */
22 | public enum TlsVersion {
23 | TLS_1_2("TLSv1.2"), // 2008.
24 | TLS_1_1("TLSv1.1"), // 2006.
25 | TLS_1_0("TLSv1"), // 1999.
26 | SSL_3_0("SSLv3"), // 1996.
27 | ;
28 |
29 | final String javaName;
30 |
31 | TlsVersion(String javaName) {
32 | this.javaName = javaName;
33 | }
34 |
35 | public static TlsVersion forJavaName(String javaName) {
36 | switch (javaName) {
37 | case "TLSv1.2":
38 | return TLS_1_2;
39 | case "TLSv1.1":
40 | return TLS_1_1;
41 | case "TLSv1":
42 | return TLS_1_0;
43 | case "SSLv3":
44 | return SSL_3_0;
45 | }
46 | throw new IllegalArgumentException("Unexpected TLS version: " + javaName);
47 | }
48 |
49 | public String javaName() {
50 | return javaName;
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/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 response.
36 | */
37 | public boolean failIfHeadersAbsent() {
38 | return this == SPDY_HEADERS;
39 | }
40 |
41 | /**
42 | * Returns true if it is an error these headers to be update existing headers of a response.
43 | */
44 | public boolean failIfHeadersPresent() {
45 | return this == SPDY_REPLY;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/samples/guide/src/main/java/okhttp3/recipes/PostForm.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.recipes;
17 |
18 | import java.io.IOException;
19 | import okhttp3.FormBody;
20 | import okhttp3.OkHttpClient;
21 | import okhttp3.Request;
22 | import okhttp3.RequestBody;
23 | import okhttp3.Response;
24 |
25 | public final class PostForm {
26 | private final OkHttpClient client = new OkHttpClient();
27 |
28 | public void run() throws Exception {
29 | RequestBody formBody = new FormBody.Builder()
30 | .add("search", "Jurassic Park")
31 | .build();
32 | Request request = new Request.Builder()
33 | .url("https://en.wikipedia.org/w/index.php")
34 | .post(formBody)
35 | .build();
36 |
37 | Response response = client.newCall(request).execute();
38 | if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
39 |
40 | System.out.println(response.body().string());
41 | }
42 |
43 | public static void main(String... args) throws Exception {
44 | new PostForm().run();
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/samples/guide/src/main/java/okhttp3/recipes/ConfigureTimeouts.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.recipes;
17 |
18 | import java.util.concurrent.TimeUnit;
19 | import okhttp3.OkHttpClient;
20 | import okhttp3.Request;
21 | import okhttp3.Response;
22 |
23 | public final class ConfigureTimeouts {
24 | private final OkHttpClient client;
25 |
26 | public ConfigureTimeouts() throws Exception {
27 | client = new OkHttpClient.Builder()
28 | .connectTimeout(10, TimeUnit.SECONDS)
29 | .writeTimeout(10, TimeUnit.SECONDS)
30 | .readTimeout(30, TimeUnit.SECONDS)
31 | .build();
32 | }
33 |
34 | public void run() throws Exception {
35 | Request request = new Request.Builder()
36 | .url("http://httpbin.org/delay/2") // This URL is served with a 2 second delay.
37 | .build();
38 |
39 | Response response = client.newCall(request).execute();
40 | System.out.println("Response completed: " + response);
41 | }
42 |
43 | public static void main(String... args) throws Exception {
44 | new ConfigureTimeouts().run();
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/samples/guide/src/main/java/okhttp3/recipes/SynchronousGet.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.recipes;
17 |
18 | import java.io.IOException;
19 | import okhttp3.Headers;
20 | import okhttp3.OkHttpClient;
21 | import okhttp3.Request;
22 | import okhttp3.Response;
23 |
24 | public final class SynchronousGet {
25 | private final OkHttpClient client = new OkHttpClient();
26 |
27 | public void run() throws Exception {
28 | Request request = new Request.Builder()
29 | .url("https://publicobject.com/helloworld.txt")
30 | .build();
31 |
32 | Response response = client.newCall(request).execute();
33 | if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
34 |
35 | Headers responseHeaders = response.headers();
36 | for (int i = 0; i < responseHeaders.size(); i++) {
37 | System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
38 | }
39 |
40 | System.out.println(response.body().string());
41 | }
42 |
43 | public static void main(String... args) throws Exception {
44 | new SynchronousGet().run();
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/okhttp/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 4.0.0
5 |
6 |
7 | com.squareup.okhttp3
8 | parent
9 | 3.1.0-SNAPSHOT
10 |
11 |
12 | okhttp
13 | OkHttp
14 |
15 |
16 |
17 | com.squareup.okio
18 | okio
19 |
20 |
21 | com.google.android
22 | android
23 | provided
24 |
25 |
26 |
27 |
28 |
29 |
30 | org.codehaus.mojo
31 | templating-maven-plugin
32 | 1.0-alpha-3
33 |
34 |
35 |
36 | filter-sources
37 |
38 |
39 |
40 |
41 |
42 | org.apache.maven.plugins
43 | maven-javadoc-plugin
44 |
45 | okhttp3.internal:okhttp3.internal.*
46 |
47 | http://square.github.io/okio/
48 |
49 |
50 |
51 |
52 |
53 |
54 |
--------------------------------------------------------------------------------
/okhttp/src/main/java/okhttp3/internal/http/RequestLine.java:
--------------------------------------------------------------------------------
1 | package okhttp3.internal.http;
2 |
3 | import java.net.HttpURLConnection;
4 | import java.net.Proxy;
5 | import okhttp3.HttpUrl;
6 | import okhttp3.Request;
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 to the application by
14 | * {@link HttpURLConnection#getHeaderFields}, so it needs to be set even if the transport is
15 | * 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 and port (like "GET
34 | * http://android.com/foo HTTP/1.1") or only the path (like "GET /foo HTTP/1.1").
35 | */
36 | private static boolean includeAuthorityInRequestLine(Request request, Proxy.Type proxyType) {
37 | return !request.isHttps() && proxyType == Proxy.Type.HTTP;
38 | }
39 |
40 | /**
41 | * Returns the path to request, like the '/' in 'GET / HTTP/1.1'. Never empty, even if the request
42 | * URL is. Includes the query component if it exists.
43 | */
44 | public static String requestPath(HttpUrl url) {
45 | String path = url.encodedPath();
46 | String query = url.encodedQuery();
47 | return query != null ? (path + '?' + query) : path;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/samples/guide/src/main/java/okhttp3/recipes/PostFile.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.recipes;
17 |
18 | import java.io.File;
19 | import java.io.IOException;
20 | import okhttp3.MediaType;
21 | import okhttp3.OkHttpClient;
22 | import okhttp3.Request;
23 | import okhttp3.RequestBody;
24 | import okhttp3.Response;
25 |
26 | public final class PostFile {
27 | public static final MediaType MEDIA_TYPE_MARKDOWN
28 | = MediaType.parse("text/x-markdown; charset=utf-8");
29 |
30 | private final OkHttpClient client = new OkHttpClient();
31 |
32 | public void run() throws Exception {
33 | File file = new File("README.md");
34 |
35 | Request request = new Request.Builder()
36 | .url("https://api.github.com/markdown/raw")
37 | .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
38 | .build();
39 |
40 | Response response = client.newCall(request).execute();
41 | if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
42 |
43 | System.out.println(response.body().string());
44 | }
45 |
46 | public static void main(String... args) throws Exception {
47 | new PostFile().run();
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/samples/guide/src/main/java/okhttp3/recipes/AccessHeaders.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.recipes;
17 |
18 | import java.io.IOException;
19 | import okhttp3.OkHttpClient;
20 | import okhttp3.Request;
21 | import okhttp3.Response;
22 |
23 | public final class AccessHeaders {
24 | private final OkHttpClient client = new OkHttpClient();
25 |
26 | public void run() throws Exception {
27 | Request request = new Request.Builder()
28 | .url("https://api.github.com/repos/square/okhttp/issues")
29 | .header("User-Agent", "OkHttp Headers.java")
30 | .addHeader("Accept", "application/json; q=0.5")
31 | .addHeader("Accept", "application/vnd.github.v3+json")
32 | .build();
33 |
34 | Response response = client.newCall(request).execute();
35 | if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
36 |
37 | System.out.println("Server: " + response.header("Server"));
38 | System.out.println("Date: " + response.header("Date"));
39 | System.out.println("Vary: " + response.headers("Vary"));
40 | }
41 |
42 | public static void main(String... args) throws Exception {
43 | new AccessHeaders().run();
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/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 connectivity problem or
23 | * timeout. Because networks can fail during an exchange, it is possible that the remote server
24 | * accepted the request before the failure.
25 | */
26 | void onFailure(Call call, IOException e);
27 |
28 | /**
29 | * Called when the HTTP response was successfully returned by the remote server. The callback may
30 | * proceed to read the response body with {@link Response#body}. The response is still live until
31 | * its response body is closed with {@code response.body().close()}. The recipient of the callback
32 | * may even consume the response body on another thread.
33 | *
34 | *
Note that transport-layer success (receiving a HTTP response code, headers and body) does
35 | * not necessarily indicate application-layer success: {@code response} may still indicate an
36 | * unhappy HTTP response code like 404 or 500.
37 | */
38 | void onResponse(Call call, Response response) throws IOException;
39 | }
40 |
--------------------------------------------------------------------------------
/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-urlconnection/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 4.0.0
5 |
6 |
7 | com.squareup.okhttp3
8 | parent
9 | 3.1.0-SNAPSHOT
10 |
11 |
12 | okhttp-urlconnection
13 | OkHttp URLConnection
14 |
15 |
16 |
17 | ${project.groupId}
18 | okhttp
19 | ${project.version}
20 |
21 |
22 | ${project.groupId}
23 | okhttp-testing-support
24 | ${project.version}
25 | test
26 |
27 |
28 |
29 | junit
30 | junit
31 | test
32 |
33 |
34 | ${project.groupId}
35 | mockwebserver
36 | ${project.version}
37 | test
38 |
39 |
40 |
41 |
42 |
43 |
44 | org.apache.maven.plugins
45 | maven-javadoc-plugin
46 |
47 | okhttp3.internal:okhttp3.internal.*
48 |
49 | http://square.github.io/okhttp/javadoc/
50 |
51 |
52 |
53 |
54 |
55 |
56 |
--------------------------------------------------------------------------------
/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 java.util.LinkedHashSet;
19 | import java.util.Set;
20 | import okhttp3.Route;
21 |
22 | /**
23 | * A blacklist of failed routes to avoid when creating a new connection to a target address. This is
24 | * used so that OkHttp can learn from its mistakes: if there was a failure attempting to connect to
25 | * a specific IP address or proxy server, that failure is remembered and alternate routes are
26 | * 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 |
--------------------------------------------------------------------------------
/samples/guide/src/main/java/okhttp3/recipes/PostString.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.recipes;
17 |
18 | import java.io.IOException;
19 | import okhttp3.MediaType;
20 | import okhttp3.OkHttpClient;
21 | import okhttp3.Request;
22 | import okhttp3.RequestBody;
23 | import okhttp3.Response;
24 |
25 | public final class PostString {
26 | public static final MediaType MEDIA_TYPE_MARKDOWN
27 | = MediaType.parse("text/x-markdown; charset=utf-8");
28 |
29 | private final OkHttpClient client = new OkHttpClient();
30 |
31 | public void run() throws Exception {
32 | String postBody = ""
33 | + "Releases\n"
34 | + "--------\n"
35 | + "\n"
36 | + " * _1.0_ May 6, 2013\n"
37 | + " * _1.1_ June 15, 2013\n"
38 | + " * _1.2_ August 11, 2013\n";
39 |
40 | Request request = new Request.Builder()
41 | .url("https://api.github.com/markdown/raw")
42 | .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))
43 | .build();
44 |
45 | Response response = client.newCall(request).execute();
46 | if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
47 |
48 | System.out.println(response.body().string());
49 | }
50 |
51 | public static void main(String... args) throws Exception {
52 | new PostString().run();
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/okhttp-tests/src/test/java/okhttp3/internal/http/RecordingProxySelector.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 java.net.InetSocketAddress;
20 | import java.net.Proxy;
21 | import java.net.ProxySelector;
22 | import java.net.SocketAddress;
23 | import java.net.URI;
24 | import java.util.ArrayList;
25 | import java.util.Arrays;
26 | import java.util.List;
27 |
28 | import static org.junit.Assert.assertEquals;
29 |
30 | public final class RecordingProxySelector extends ProxySelector {
31 | public final List proxies = new ArrayList<>();
32 | public final List requestedUris = new ArrayList<>();
33 | public final List failures = new ArrayList<>();
34 |
35 | @Override public List select(URI uri) {
36 | requestedUris.add(uri);
37 | return proxies;
38 | }
39 |
40 | public void assertRequests(URI... expectedUris) {
41 | assertEquals(Arrays.asList(expectedUris), requestedUris);
42 | requestedUris.clear();
43 | }
44 |
45 | @Override public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
46 | InetSocketAddress socketAddress = (InetSocketAddress) sa;
47 | failures.add(
48 | String.format("%s %s:%d %s", uri, socketAddress.getHostName(), socketAddress.getPort(),
49 | ioe.getMessage()));
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/samples/guide/src/main/java/okhttp3/recipes/ParseResponseWithGson.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.recipes;
17 |
18 | import com.google.gson.Gson;
19 | import java.io.IOException;
20 | import java.util.Map;
21 | import okhttp3.OkHttpClient;
22 | import okhttp3.Request;
23 | import okhttp3.Response;
24 |
25 | public final class ParseResponseWithGson {
26 | private final OkHttpClient client = new OkHttpClient();
27 | private final Gson gson = new Gson();
28 |
29 | public void run() throws Exception {
30 | Request request = new Request.Builder()
31 | .url("https://api.github.com/gists/c2a7c39532239ff261be")
32 | .build();
33 | Response response = client.newCall(request).execute();
34 | if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
35 |
36 | Gist gist = gson.fromJson(response.body().charStream(), Gist.class);
37 | for (Map.Entry entry : gist.files.entrySet()) {
38 | System.out.println(entry.getKey());
39 | System.out.println(entry.getValue().content);
40 | }
41 | }
42 |
43 | static class Gist {
44 | Map files;
45 | }
46 |
47 | static class GistFile {
48 | String content;
49 | }
50 |
51 | public static void main(String... args) throws Exception {
52 | new ParseResponseWithGson().run();
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/okhttp-tests/src/test/java/okhttp3/TestUtil.java:
--------------------------------------------------------------------------------
1 | package okhttp3;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Arrays;
5 | import java.util.Collection;
6 | import java.util.LinkedHashSet;
7 | import java.util.List;
8 | import java.util.Set;
9 | import okhttp3.internal.SingleInetAddressDns;
10 | import okhttp3.internal.framed.Header;
11 |
12 | public final class TestUtil {
13 | private TestUtil() {
14 | }
15 |
16 | private static final ConnectionPool connectionPool = new ConnectionPool();
17 |
18 | /**
19 | * Returns an OkHttpClient for all tests to use as a starting point.
20 | *
21 | *
The shared instance allows all tests to share a single connection pool, which prevents idle
22 | * connections from consuming unnecessary resources while connections wait to be evicted.
23 | *
24 | *
This client is also configured to be slightly more deterministic, returning a single IP
25 | * address for all hosts, regardless of the actual number of IP addresses reported by DNS.
26 | */
27 | public static OkHttpClient defaultClient() {
28 | return new OkHttpClient.Builder()
29 | .connectionPool(connectionPool)
30 | .dns(new SingleInetAddressDns()) // Prevent unexpected fallback addresses.
31 | .build();
32 | }
33 |
34 | public static List headerEntries(String... elements) {
35 | List result = new ArrayList<>(elements.length / 2);
36 | for (int i = 0; i < elements.length; i += 2) {
37 | result.add(new Header(elements[i], elements[i + 1]));
38 | }
39 | return result;
40 | }
41 |
42 | public static Set setOf(T... elements) {
43 | return setOf(Arrays.asList(elements));
44 | }
45 |
46 | public static Set setOf(Collection elements) {
47 | return new LinkedHashSet<>(elements);
48 | }
49 |
50 | public static String repeat(char c, int count) {
51 | char[] array = new char[count];
52 | Arrays.fill(array, c);
53 | return new String(array);
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/okhttp-tests/src/test/java/okhttp3/internal/http/RouteExceptionTest.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 org.junit.Test;
20 |
21 | import static org.junit.Assert.assertSame;
22 |
23 | public class RouteExceptionTest {
24 |
25 | @Test public void getConnectionIOException_single() {
26 | IOException firstException = new IOException();
27 | RouteException re = new RouteException(firstException);
28 | assertSame(firstException, re.getLastConnectException());
29 | }
30 |
31 | @Test public void getConnectionIOException_multiple() {
32 | IOException firstException = new IOException();
33 | IOException secondException = new IOException();
34 | IOException thirdException = new IOException();
35 | RouteException re = new RouteException(firstException);
36 | re.addConnectException(secondException);
37 | re.addConnectException(thirdException);
38 |
39 | IOException connectionIOException = re.getLastConnectException();
40 | assertSame(thirdException, connectionIOException);
41 | Throwable[] thirdSuppressedExceptions = thirdException.getSuppressed();
42 | assertSame(secondException, thirdSuppressedExceptions[0]);
43 |
44 | Throwable[] secondSuppressedException = secondException.getSuppressed();
45 | assertSame(firstException, secondSuppressedException[0]);
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/okhttp-tests/src/test/java/okhttp3/internal/RecordingAuthenticator.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2013 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 | package okhttp3.internal;
17 |
18 | import java.net.Authenticator;
19 | import java.net.PasswordAuthentication;
20 | import java.util.ArrayList;
21 | import java.util.List;
22 |
23 | public final class RecordingAuthenticator extends Authenticator {
24 | /** base64("username:password") */
25 | public static final String BASE_64_CREDENTIALS = "dXNlcm5hbWU6cGFzc3dvcmQ=";
26 |
27 | public final List calls = new ArrayList<>();
28 | public final PasswordAuthentication authentication;
29 |
30 | public RecordingAuthenticator(PasswordAuthentication authentication) {
31 | this.authentication = authentication;
32 | }
33 |
34 | public RecordingAuthenticator() {
35 | this(new PasswordAuthentication("username", "password".toCharArray()));
36 | }
37 |
38 | @Override protected PasswordAuthentication getPasswordAuthentication() {
39 | this.calls.add("host=" + getRequestingHost()
40 | + " port=" + getRequestingPort()
41 | + " site=" + getRequestingSite().getHostName()
42 | + " url=" + getRequestingURL()
43 | + " type=" + getRequestorType()
44 | + " prompt=" + getRequestingPrompt()
45 | + " protocol=" + getRequestingProtocol()
46 | + " scheme=" + getRequestingScheme());
47 | return authentication;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/okhttp-tests/src/test/java/okhttp3/internal/RecordingOkAuthenticator.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 java.io.IOException;
19 | import java.net.Proxy;
20 | import java.util.ArrayList;
21 | import java.util.List;
22 | import okhttp3.Authenticator;
23 | import okhttp3.Request;
24 | import okhttp3.Response;
25 | import okhttp3.Route;
26 |
27 | public final class RecordingOkAuthenticator implements Authenticator {
28 | public final List responses = new ArrayList<>();
29 | public final List proxies = new ArrayList<>();
30 | public final String credential;
31 |
32 | public RecordingOkAuthenticator(String credential) {
33 | this.credential = credential;
34 | }
35 |
36 | public Response onlyResponse() {
37 | if (responses.size() != 1) throw new IllegalStateException();
38 | return responses.get(0);
39 | }
40 |
41 | public Proxy onlyProxy() {
42 | if (proxies.size() != 1) throw new IllegalStateException();
43 | return proxies.get(0);
44 | }
45 |
46 | @Override public Request authenticate(Route route, Response response) throws IOException {
47 | responses.add(response);
48 | proxies.add(route.proxy());
49 | String header = response.code() == 407 ? "Proxy-Authorization" : "Authorization";
50 | return response.request().newBuilder()
51 | .addHeader(header, credential)
52 | .build();
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/benchmarks/src/main/java/okhttp3/benchmarks/SynchronousHttpClient.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.benchmarks;
17 |
18 | import java.io.IOException;
19 | import java.io.InputStream;
20 | import java.util.concurrent.LinkedBlockingQueue;
21 | import java.util.concurrent.ThreadPoolExecutor;
22 | import java.util.concurrent.TimeUnit;
23 | import okhttp3.HttpUrl;
24 |
25 | /** Any HTTP client with a blocking API. */
26 | abstract class SynchronousHttpClient implements HttpClient {
27 | ThreadPoolExecutor executor;
28 | int targetBacklog;
29 |
30 | @Override public void prepare(Benchmark benchmark) {
31 | this.targetBacklog = benchmark.targetBacklog;
32 | executor = new ThreadPoolExecutor(benchmark.concurrencyLevel, benchmark.concurrencyLevel,
33 | 1, TimeUnit.SECONDS, new LinkedBlockingQueue());
34 | }
35 |
36 | @Override public void enqueue(HttpUrl url) {
37 | executor.execute(request(url));
38 | }
39 |
40 | @Override public boolean acceptingJobs() {
41 | return executor.getQueue().size() < targetBacklog;
42 | }
43 |
44 | static long readAllAndClose(InputStream in) throws IOException {
45 | byte[] buffer = new byte[1024];
46 | long total = 0;
47 | for (int count; (count = in.read(buffer)) != -1; ) {
48 | total += count;
49 | }
50 | in.close();
51 | return total;
52 | }
53 |
54 | abstract Runnable request(HttpUrl url);
55 | }
56 |
--------------------------------------------------------------------------------
/okhttp-android-support/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 4.0.0
5 |
6 |
7 | com.squareup.okhttp3
8 | parent
9 | 3.1.0-SNAPSHOT
10 |
11 |
12 | okhttp-android-support
13 | OkHttp Android Platform Support
14 | Classes to support the Android platform's use of OkHttp (not required for most
15 | developers).
16 |
17 |
18 |
19 |
20 | ${project.groupId}
21 | okhttp-testing-support
22 | ${project.version}
23 | test
24 |
25 |
26 | ${project.groupId}
27 | okhttp-urlconnection
28 | ${project.version}
29 |
30 |
31 |
32 | junit
33 | junit
34 | test
35 |
36 |
37 | ${project.groupId}
38 | mockwebserver
39 | ${project.version}
40 | test
41 |
42 |
43 |
44 |
45 |
46 |
47 | org.apache.maven.plugins
48 | maven-javadoc-plugin
49 |
50 | okhttp3.internal.*
51 |
52 | http://square.github.io/okhttp/javadoc/
53 |
54 |
55 |
56 |
57 |
58 |
59 |
--------------------------------------------------------------------------------
/samples/guide/src/main/java/okhttp3/recipes/AsynchronousGet.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.recipes;
17 |
18 | import java.io.IOException;
19 | import okhttp3.Call;
20 | import okhttp3.Callback;
21 | import okhttp3.Headers;
22 | import okhttp3.OkHttpClient;
23 | import okhttp3.Request;
24 | import okhttp3.Response;
25 |
26 | public final class AsynchronousGet {
27 | private final OkHttpClient client = new OkHttpClient();
28 |
29 | public void run() throws Exception {
30 | Request request = new Request.Builder()
31 | .url("http://publicobject.com/helloworld.txt")
32 | .build();
33 |
34 | client.newCall(request).enqueue(new Callback() {
35 | @Override public void onFailure(Call call, IOException e) {
36 | e.printStackTrace();
37 | }
38 |
39 | @Override public void onResponse(Call call, Response response) throws IOException {
40 | if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
41 |
42 | Headers responseHeaders = response.headers();
43 | for (int i = 0, size = responseHeaders.size(); i < size; i++) {
44 | System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
45 | }
46 |
47 | System.out.println(response.body().string());
48 | }
49 | });
50 | }
51 |
52 | public static void main(String... args) throws Exception {
53 | new AsynchronousGet().run();
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/samples/simple-client/src/main/java/okhttp3/sample/OkHttpContributors.java:
--------------------------------------------------------------------------------
1 | package okhttp3.sample;
2 |
3 | import com.google.gson.Gson;
4 | import com.google.gson.reflect.TypeToken;
5 | import java.io.Reader;
6 | import java.util.Collections;
7 | import java.util.Comparator;
8 | import java.util.List;
9 | import okhttp3.OkHttpClient;
10 | import okhttp3.Request;
11 | import okhttp3.Response;
12 | import okhttp3.ResponseBody;
13 |
14 | public class OkHttpContributors {
15 | private static final String ENDPOINT = "https://api.github.com/repos/square/okhttp/contributors";
16 | private static final Gson GSON = new Gson();
17 | private static final TypeToken> CONTRIBUTORS =
18 | new TypeToken>() {
19 | };
20 |
21 | static class Contributor {
22 | String login;
23 | int contributions;
24 | }
25 |
26 | public static void main(String... args) throws Exception {
27 | OkHttpClient client = new OkHttpClient();
28 |
29 | // Create request for remote resource.
30 | Request request = new Request.Builder()
31 | .url(ENDPOINT)
32 | .build();
33 |
34 | // Execute the request and retrieve the response.
35 | Response response = client.newCall(request).execute();
36 |
37 | // Deserialize HTTP response to concrete type.
38 | ResponseBody body = response.body();
39 | Reader charStream = body.charStream();
40 | List contributors = GSON.fromJson(charStream, CONTRIBUTORS.getType());
41 | body.close();
42 |
43 | // Sort list by the most contributions.
44 | Collections.sort(contributors, new Comparator() {
45 | @Override public int compare(Contributor c1, Contributor c2) {
46 | return c2.contributions - c1.contributions;
47 | }
48 | });
49 |
50 | // Output list of contributors.
51 | for (Contributor contributor : contributors) {
52 | System.out.println(contributor.login + ": " + contributor.contributions);
53 | }
54 | }
55 |
56 | private OkHttpContributors() {
57 | // No instances.
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/okhttp-tests/src/test/java/okhttp3/internal/framed/HuffmanTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013 Twitter, 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.ByteArrayOutputStream;
19 | import java.io.DataOutputStream;
20 | import java.io.IOException;
21 | import java.util.Arrays;
22 | import java.util.Random;
23 | import org.junit.Test;
24 |
25 | import static org.junit.Assert.assertEquals;
26 | import static org.junit.Assert.assertTrue;
27 |
28 | /**
29 | * Original version of this class was lifted from {@code com.twitter.hpack.HuffmanTest}.
30 | */
31 | public class HuffmanTest {
32 |
33 | @Test public void roundTripForRequestAndResponse() throws IOException {
34 | String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
35 | for (int i = 0; i < s.length(); i++) {
36 | assertRoundTrip(s.substring(0, i).getBytes());
37 | }
38 |
39 | Random random = new Random(123456789L);
40 | byte[] buf = new byte[4096];
41 | random.nextBytes(buf);
42 | assertRoundTrip(buf);
43 | }
44 |
45 | private void assertRoundTrip(byte[] buf) throws IOException {
46 | ByteArrayOutputStream baos = new ByteArrayOutputStream();
47 | DataOutputStream dos = new DataOutputStream(baos);
48 |
49 | Huffman.get().encode(buf, dos);
50 | assertEquals(baos.size(), Huffman.get().encodedLength(buf));
51 |
52 | byte[] decodedBytes = Huffman.get().decode(baos.toByteArray());
53 | assertTrue(Arrays.equals(buf, decodedBytes));
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/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 java.io.IOException;
19 | import okhttp3.Request;
20 | import okhttp3.Response;
21 | import okhttp3.internal.http.CacheRequest;
22 | import okhttp3.internal.http.CacheStrategy;
23 |
24 | /**
25 | * OkHttp's internal cache interface. Applications shouldn't implement this: instead use {@link
26 | * okhttp3.Cache}.
27 | */
28 | public interface InternalCache {
29 | Response get(Request request) throws IOException;
30 |
31 | CacheRequest put(Response response) throws IOException;
32 |
33 | /**
34 | * Remove any cache entries for the supplied {@code request}. This is invoked when the client
35 | * invalidates the cache, such as when making POST requests.
36 | */
37 | void remove(Request request) throws IOException;
38 |
39 | /**
40 | * Handles a conditional request hit by updating the stored cache response with the headers from
41 | * {@code network}. The cached response body is not updated. If the stored response has changed
42 | * since {@code cached} was returned, this does nothing.
43 | */
44 | void update(Response cached, Response network) throws IOException;
45 |
46 | /** Track an conditional GET that was satisfied by this cache. */
47 | void trackConditionalCacheHit();
48 |
49 | /** Track an HTTP response being satisfied with {@code cacheStrategy}. */
50 | void trackResponse(CacheStrategy cacheStrategy);
51 | }
52 |
--------------------------------------------------------------------------------
/okhttp-android-support/src/main/java/okhttp3/AndroidInternal.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;
17 |
18 | import java.net.ResponseCache;
19 | import okhttp3.internal.huc.CacheAdapter;
20 |
21 | /**
22 | * Back doors to enable the use of OkHttp within the Android platform libraries. OkHttp is used to
23 | * provide the default {@link java.net.HttpURLConnection} / {@link javax.net.ssl.HttpsURLConnection}
24 | * implementation including support for a custom {@link ResponseCache}.
25 | */
26 | public class AndroidInternal {
27 |
28 | private AndroidInternal() {
29 | }
30 |
31 | /** Sets the response cache to be used to read and write cached responses. */
32 | public static void setResponseCache(OkUrlFactory okUrlFactory, ResponseCache responseCache) {
33 | OkHttpClient.Builder builder = okUrlFactory.client().newBuilder();
34 | if (responseCache instanceof OkCacheContainer) {
35 | // Avoid adding layers of wrappers. Rather than wrap the ResponseCache in yet another layer to
36 | // make the ResponseCache look like an InternalCache, we can unwrap the Cache instead.
37 | // This means that Cache stats will be correctly updated.
38 | OkCacheContainer okCacheContainer = (OkCacheContainer) responseCache;
39 | builder.cache(okCacheContainer.getCache());
40 | } else {
41 | builder.setInternalCache(responseCache != null ? new CacheAdapter(responseCache) : null);
42 | }
43 | okUrlFactory.setClient(builder.build());
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/okhttp-hpacktests/src/test/java/okhttp3/internal/spdy/hpackjson/Story.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.spdy.hpackjson;
17 |
18 | import java.util.ArrayList;
19 | import java.util.List;
20 |
21 | /**
22 | * Representation of one story, a set of request headers to encode or decode. This class is used
23 | * reflectively with Gson to parse stories from files.
24 | */
25 | public class Story implements Cloneable {
26 |
27 | private transient String fileName;
28 | private List cases;
29 | private int draft;
30 | private String description;
31 |
32 | /**
33 | * The filename is only used in the toString representation.
34 | */
35 | void setFileName(String fileName) {
36 | this.fileName = fileName;
37 | }
38 |
39 | public List getCases() {
40 | return cases;
41 | }
42 |
43 | /** We only expect stories that match the draft we've implemented to pass. */
44 | public int getDraft() {
45 | return draft;
46 | }
47 |
48 | @Override
49 | public Story clone() throws CloneNotSupportedException {
50 | Story story = new Story();
51 | story.fileName = this.fileName;
52 | story.cases = new ArrayList<>();
53 | for (Case caze : cases) {
54 | story.cases.add(caze.clone());
55 | }
56 | story.draft = draft;
57 | story.description = description;
58 | return story;
59 | }
60 |
61 | @Override
62 | public String toString() {
63 | // Used as the test name.
64 | return fileName;
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/okhttp-tests/src/test/java/okhttp3/internal/http/FakeDns.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.http;
17 |
18 | import java.net.InetAddress;
19 | import java.net.UnknownHostException;
20 | import java.util.ArrayList;
21 | import java.util.Arrays;
22 | import java.util.Collections;
23 | import java.util.List;
24 | import okhttp3.Dns;
25 |
26 | import static org.junit.Assert.assertEquals;
27 |
28 | public final class FakeDns implements Dns {
29 | private List requestedHosts = new ArrayList<>();
30 | private List addresses = Collections.emptyList();
31 |
32 | /** Sets the addresses to be returned by this fake DNS service. */
33 | public FakeDns addresses(List addresses) {
34 | this.addresses = new ArrayList<>(addresses);
35 | return this;
36 | }
37 |
38 | /** Sets the service to throw when a hostname is requested. */
39 | public FakeDns unknownHost() {
40 | this.addresses = Collections.emptyList();
41 | return this;
42 | }
43 |
44 | public InetAddress address(int index) {
45 | return addresses.get(index);
46 | }
47 |
48 | @Override public List lookup(String hostname) throws UnknownHostException {
49 | requestedHosts.add(hostname);
50 | if (addresses.isEmpty()) throw new UnknownHostException();
51 | return addresses;
52 | }
53 |
54 | public void assertRequests(String... expectedHosts) {
55 | assertEquals(Arrays.asList(expectedHosts), requestedHosts);
56 | requestedHosts.clear();
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/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-testing-support/src/main/java/okhttp3/RecordingCookieJar.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;
17 |
18 | import java.util.ArrayDeque;
19 | import java.util.ArrayList;
20 | import java.util.Arrays;
21 | import java.util.Collections;
22 | import java.util.Deque;
23 | import java.util.List;
24 |
25 | import static org.junit.Assert.assertEquals;
26 |
27 | public final class RecordingCookieJar implements CookieJar {
28 | private final Deque> requestCookies = new ArrayDeque<>();
29 | private final Deque> responseCookies = new ArrayDeque<>();
30 |
31 | public void enqueueRequestCookies(Cookie... cookies) {
32 | requestCookies.add(Arrays.asList(cookies));
33 | }
34 |
35 | public List takeResponseCookies() {
36 | return responseCookies.removeFirst();
37 | }
38 |
39 | public void assertResponseCookies(String... cookies) {
40 | List actualCookies = takeResponseCookies();
41 | List actualCookieStrings = new ArrayList<>();
42 | for (Cookie cookie : actualCookies) {
43 | actualCookieStrings.add(cookie.toString());
44 | }
45 | assertEquals(Arrays.asList(cookies), actualCookieStrings);
46 | }
47 |
48 | @Override public void saveFromResponse(HttpUrl url, List cookies) {
49 | responseCookies.add(cookies);
50 | }
51 |
52 | @Override public List loadForRequest(HttpUrl url) {
53 | if (requestCookies.isEmpty()) return Collections.emptyList();
54 | return requestCookies.removeFirst();
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/okhttp-hpacktests/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
6 | 4.0.0
7 |
8 |
9 | com.squareup.okhttp3
10 | parent
11 | 3.0.0-SNAPSHOT
12 |
13 |
14 | okhttp-hpacktests
15 | OkHttp HPACK Tests
16 |
17 |
18 |
19 | com.squareup.okio
20 | okio
21 |
22 |
23 | ${project.groupId}
24 | okhttp
25 | ${project.version}
26 |
27 |
28 | ${project.groupId}
29 | okhttp-testing-support
30 | ${project.version}
31 | test
32 |
33 |
34 | junit
35 | junit
36 | test
37 |
38 |
39 | ${project.groupId}
40 | mockwebserver
41 | ${project.version}
42 | test
43 |
44 |
45 |
46 | com.google.code.gson
47 | gson
48 | compile
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 | org.apache.maven.plugins
57 | maven-deploy-plugin
58 |
59 | true
60 |
61 |
62 |
63 |
64 |
65 |
--------------------------------------------------------------------------------
/okhttp-apache/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 4.0.0
5 |
6 |
7 | com.squareup.okhttp3
8 | parent
9 | 3.1.0-SNAPSHOT
10 |
11 |
12 | okhttp-apache
13 | OkHttp Apache HttpClient
14 |
15 |
16 |
17 | ${project.groupId}
18 | okhttp
19 | ${project.version}
20 |
21 |
22 | ${project.groupId}
23 | okhttp-testing-support
24 | ${project.version}
25 | test
26 |
27 |
28 | org.apache.httpcomponents
29 | httpclient
30 | provided
31 |
32 |
33 |
34 | junit
35 | junit
36 | test
37 |
38 |
39 | ${project.groupId}
40 | mockwebserver
41 | ${project.version}
42 | test
43 |
44 |
45 |
46 |
47 |
48 |
49 | org.apache.maven.plugins
50 | maven-javadoc-plugin
51 |
52 |
53 | http://square.github.io/okhttp/javadoc/
54 | http://hc.apache.org/httpcomponents-client-4.3.x/httpclient/apidocs/
55 | https://hc.apache.org/httpcomponents-core-4.3.x/httpcore/apidocs/
56 |
57 |
58 |
59 |
60 |
61 |
62 |
--------------------------------------------------------------------------------
/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 |
29 | static {
30 | Method m;
31 | try {
32 | m = Throwable.class.getDeclaredMethod("addSuppressed", Throwable.class);
33 | } catch (Exception e) {
34 | m = null;
35 | }
36 | addSuppressedExceptionMethod = m;
37 | }
38 |
39 | private IOException lastException;
40 |
41 | public RouteException(IOException cause) {
42 | super(cause);
43 | lastException = cause;
44 | }
45 |
46 | public IOException getLastConnectException() {
47 | return lastException;
48 | }
49 |
50 | public void addConnectException(IOException e) {
51 | addSuppressedIfPossible(e, lastException);
52 | lastException = e;
53 | }
54 |
55 | private void addSuppressedIfPossible(IOException e, IOException suppressed) {
56 | if (addSuppressedExceptionMethod != null) {
57 | try {
58 | addSuppressedExceptionMethod.invoke(e, suppressed);
59 | } catch (InvocationTargetException | IllegalAccessException ignored) {
60 | }
61 | }
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | OkHttp
2 | ======
3 |
4 | An HTTP & HTTP/2 client for Android and Java applications. For more information see [the website][1] and [the wiki][2].
5 |
6 | Download
7 | --------
8 |
9 | Download [the latest JAR][3] or grab via Maven:
10 | ```xml
11 |
12 | com.squareup.okhttp3
13 | okhttp
14 | 3.0.1
15 |
16 | ```
17 | or Gradle:
18 | ```groovy
19 | compile 'com.squareup.okhttp3:okhttp:3.0.1'
20 | ```
21 |
22 | Snapshots of the development version are available in [Sonatype's `snapshots` repository][snap].
23 |
24 |
25 | MockWebServer
26 | -------------
27 |
28 | A library for testing HTTP, HTTPS, HTTP/2.0, and SPDY clients.
29 |
30 | MockWebServer coupling with OkHttp is essential for proper testing of HTTP/2.0 so that code can be shared.
31 |
32 | ### Download
33 |
34 | Download [the latest JAR][4] or grab via Maven:
35 | ```xml
36 |
37 | com.squareup.okhttp3
38 | mockwebserver
39 | 3.0.1
40 | test
41 |
42 | ```
43 | or Gradle:
44 | ```groovy
45 | testCompile 'com.squareup.okhttp3:mockwebserver:3.0.1'
46 | ```
47 |
48 |
49 |
50 | License
51 | -------
52 |
53 | Licensed under the Apache License, Version 2.0 (the "License");
54 | you may not use this file except in compliance with the License.
55 | You may obtain a copy of the License at
56 |
57 | http://www.apache.org/licenses/LICENSE-2.0
58 |
59 | Unless required by applicable law or agreed to in writing, software
60 | distributed under the License is distributed on an "AS IS" BASIS,
61 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
62 | See the License for the specific language governing permissions and
63 | limitations under the License.
64 |
65 |
66 | [1]: http://square.github.io/okhttp
67 | [2]: https://github.com/square/okhttp/wiki
68 | [3]: https://search.maven.org/remote_content?g=com.squareup.okhttp3&a=okhttp&v=LATEST
69 | [4]: https://search.maven.org/remote_content?g=com.squareup.okhttp3&a=mockwebserver&v=LATEST
70 | [snap]: https://oss.sonatype.org/content/repositories/snapshots/
71 |
--------------------------------------------------------------------------------
/samples/guide/src/main/java/okhttp3/recipes/CertificatePinning.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.recipes;
17 |
18 | import java.io.IOException;
19 | import java.security.cert.Certificate;
20 | import okhttp3.CertificatePinner;
21 | import okhttp3.OkHttpClient;
22 | import okhttp3.Request;
23 | import okhttp3.Response;
24 |
25 | public final class CertificatePinning {
26 | private final OkHttpClient client;
27 |
28 | public CertificatePinning() {
29 | client = new OkHttpClient.Builder()
30 | .certificatePinner(
31 | new CertificatePinner.Builder()
32 | .add("publicobject.com", "sha1/DmxUShsZuNiqPQsX2Oi9uv2sCnw=")
33 | .add("publicobject.com", "sha1/SXxoaOSEzPC6BgGmxAt/EAcsajw=")
34 | .add("publicobject.com", "sha1/blhOM3W9V/bVQhsWAcLYwPU6n24=")
35 | .add("publicobject.com", "sha1/T5x9IXmcrQ7YuQxXnxoCmeeQ84c=")
36 | .build())
37 | .build();
38 | }
39 |
40 | public void run() throws Exception {
41 | Request request = new Request.Builder()
42 | .url("https://publicobject.com/robots.txt")
43 | .build();
44 |
45 | Response response = client.newCall(request).execute();
46 | if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
47 |
48 | for (Certificate certificate : response.handshake().peerCertificates()) {
49 | System.out.println(CertificatePinner.pin(certificate));
50 | }
51 | }
52 |
53 | public static void main(String... args) throws Exception {
54 | new CertificatePinning().run();
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/okhttp-hpacktests/src/test/java/okhttp3/internal/spdy/HpackRoundTripTest.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.spdy;
17 |
18 | import java.util.Collection;
19 | import okhttp3.internal.spdy.hpackjson.Case;
20 | import okhttp3.internal.spdy.hpackjson.Story;
21 | import okio.Buffer;
22 | import org.junit.Test;
23 | import org.junit.runner.RunWith;
24 | import org.junit.runners.Parameterized;
25 |
26 | /**
27 | * Tests for round-tripping headers through hpack..
28 | */
29 | // TODO: update hpack-test-case with the output of our encoder.
30 | // This test will hide complementary bugs in the encoder and decoder,
31 | // We should test that the encoder is producing responses that are
32 | // d]
33 | @RunWith(Parameterized.class)
34 | public class HpackRoundTripTest extends HpackDecodeTestBase {
35 |
36 | private static final String[] RAW_DATA = {"raw-data"};
37 |
38 | @Parameterized.Parameters(name = "{0}")
39 | public static Collection getStories() throws Exception {
40 | return createStories(RAW_DATA);
41 | }
42 |
43 | private Buffer bytesOut = new Buffer();
44 | private Hpack.Writer hpackWriter = new Hpack.Writer(bytesOut);
45 |
46 | public HpackRoundTripTest(Story story) {
47 | super(story);
48 | }
49 |
50 | @Test
51 | public void testRoundTrip() throws Exception {
52 | Story story = getStory().clone();
53 | // Mutate cases in base class.
54 | for (Case caze : story.getCases()) {
55 | hpackWriter.writeHeaders(caze.getHeaders());
56 | caze.setWire(bytesOut.readByteString());
57 | }
58 |
59 | testDecoder(story);
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/samples/static-server/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 4.0.0
5 |
6 |
7 | com.squareup.okhttp3.sample
8 | sample-parent
9 | 3.1.0-SNAPSHOT
10 |
11 |
12 | static-server
13 | Sample: Static Server
14 |
15 |
16 |
17 | com.squareup.okhttp3
18 | mockwebserver
19 | ${project.version}
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 | org.apache.maven.plugins
28 | maven-shade-plugin
29 | 2.1
30 |
31 | true
32 | shaded
33 |
34 |
35 |
36 | okhttp3.sample.SampleServer
37 |
38 |
39 |
40 |
41 |
42 | *:*
43 |
44 | META-INF/*.SF
45 | META-INF/*.DSA
46 | META-INF/*.RSA
47 |
48 |
49 |
50 |
51 |
52 |
53 | package
54 |
55 | shade
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
--------------------------------------------------------------------------------
/samples/guide/src/main/java/okhttp3/recipes/Authenticate.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.recipes;
17 |
18 | import java.io.IOException;
19 | import okhttp3.Authenticator;
20 | import okhttp3.Credentials;
21 | import okhttp3.OkHttpClient;
22 | import okhttp3.Request;
23 | import okhttp3.Response;
24 | import okhttp3.Route;
25 |
26 | public final class Authenticate {
27 | private final OkHttpClient client;
28 |
29 | public Authenticate() {
30 | client = new OkHttpClient.Builder()
31 | .authenticator(new Authenticator() {
32 | @Override public Request authenticate(Route route, Response response) throws IOException {
33 | System.out.println("Authenticating for response: " + response);
34 | System.out.println("Challenges: " + response.challenges());
35 | String credential = Credentials.basic("jesse", "password1");
36 | return response.request().newBuilder()
37 | .header("Authorization", credential)
38 | .build();
39 | }
40 | })
41 | .build();
42 | }
43 |
44 | public void run() throws Exception {
45 | Request request = new Request.Builder()
46 | .url("http://publicobject.com/secrets/hellosecret.txt")
47 | .build();
48 |
49 | Response response = client.newCall(request).execute();
50 | if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
51 |
52 | System.out.println(response.body().string());
53 | }
54 |
55 | public static void main(String... args) throws Exception {
56 | new Authenticate().run();
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/samples/guide/src/main/java/okhttp3/recipes/PerCallSettings.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.recipes;
17 |
18 | import java.io.IOException;
19 | import java.util.concurrent.TimeUnit;
20 | import okhttp3.OkHttpClient;
21 | import okhttp3.Request;
22 | import okhttp3.Response;
23 |
24 | public final class PerCallSettings {
25 | private final OkHttpClient client = new OkHttpClient();
26 |
27 | public void run() throws Exception {
28 | Request request = new Request.Builder()
29 | .url("http://httpbin.org/delay/1") // This URL is served with a 1 second delay.
30 | .build();
31 |
32 | try {
33 | // Copy to customize OkHttp for this request.
34 | OkHttpClient copy = client.newBuilder()
35 | .readTimeout(500, TimeUnit.MILLISECONDS)
36 | .build();
37 |
38 | Response response = copy.newCall(request).execute();
39 | System.out.println("Response 1 succeeded: " + response);
40 | } catch (IOException e) {
41 | System.out.println("Response 1 failed: " + e);
42 | }
43 |
44 | try {
45 | // Copy to customize OkHttp for this request.
46 | OkHttpClient copy = client.newBuilder()
47 | .readTimeout(3000, TimeUnit.MILLISECONDS)
48 | .build();
49 |
50 | Response response = copy.newCall(request).execute();
51 | System.out.println("Response 2 succeeded: " + response);
52 | } catch (IOException e) {
53 | System.out.println("Response 2 failed: " + e);
54 | }
55 | }
56 |
57 | public static void main(String... args) throws Exception {
58 | new PerCallSettings().run();
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/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. If
45 | * a connection to an address fails, OkHttp will retry the connection with the next address until
46 | * either a connection is made, the set of IP addresses is exhausted, or a limit is exceeded.
47 | */
48 | List lookup(String hostname) throws UnknownHostException;
49 | }
50 |
--------------------------------------------------------------------------------
/okhttp-tests/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 4.0.0
5 |
6 |
7 | com.squareup.okhttp3
8 | parent
9 | 3.1.0-SNAPSHOT
10 |
11 |
12 | okhttp-tests
13 | OkHttp Tests
14 |
15 |
16 |
17 | com.squareup.okio
18 | okio
19 |
20 |
21 | ${project.groupId}
22 | okhttp
23 | ${project.version}
24 |
25 |
26 | ${project.groupId}
27 | okhttp-testing-support
28 | ${project.version}
29 | test
30 |
31 |
32 | ${project.groupId}
33 | okhttp-urlconnection
34 | ${project.version}
35 |
36 |
37 |
38 | junit
39 | junit
40 | test
41 |
42 |
43 | ${project.groupId}
44 | mockwebserver
45 | ${project.version}
46 | test
47 |
48 |
49 | com.google.code.gson
50 | gson
51 | test
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 | org.apache.maven.plugins
60 | maven-deploy-plugin
61 |
62 | true
63 |
64 |
65 |
66 |
67 |
68 |
--------------------------------------------------------------------------------
/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 response to arrive if
51 | * necessary. Returns -1 if the response was canceled.
52 | */
53 | public long roundTripTime() throws InterruptedException {
54 | latch.await();
55 | return received - sent;
56 | }
57 |
58 | /**
59 | * Returns the round trip time for this ping in nanoseconds, or -1 if the response was canceled,
60 | * or -2 if the timeout elapsed before the round trip completed.
61 | */
62 | public long roundTripTime(long timeout, TimeUnit unit) throws InterruptedException {
63 | if (latch.await(timeout, unit)) {
64 | return received - sent;
65 | } else {
66 | return -2;
67 | }
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/samples/guide/src/main/java/okhttp3/recipes/LoggingInterceptors.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.recipes;
17 |
18 | import java.io.IOException;
19 | import java.util.logging.Logger;
20 | import okhttp3.Interceptor;
21 | import okhttp3.OkHttpClient;
22 | import okhttp3.Request;
23 | import okhttp3.Response;
24 |
25 | public final class LoggingInterceptors {
26 | private static final Logger logger = Logger.getLogger(LoggingInterceptors.class.getName());
27 | private final OkHttpClient client = new OkHttpClient.Builder()
28 | .addInterceptor(new LoggingInterceptor())
29 | .build();
30 |
31 | public void run() throws Exception {
32 | Request request = new Request.Builder()
33 | .url("https://publicobject.com/helloworld.txt")
34 | .build();
35 |
36 | Response response = client.newCall(request).execute();
37 | response.body().close();
38 | }
39 |
40 | private static class LoggingInterceptor implements Interceptor {
41 | @Override public Response intercept(Chain chain) throws IOException {
42 | long t1 = System.nanoTime();
43 | Request request = chain.request();
44 | logger.info(String.format("Sending request %s on %s%n%s",
45 | request.url(), chain.connection(), request.headers()));
46 | Response response = chain.proceed(request);
47 |
48 | long t2 = System.nanoTime();
49 | logger.info(String.format("Received response for %s in %.1fms%n%s",
50 | request.url(), (t2 - t1) / 1e6d, response.headers()));
51 | return response;
52 | }
53 | }
54 |
55 | public static void main(String... args) throws Exception {
56 | new LoggingInterceptors().run();
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/okhttp-hpacktests/src/test/java/okhttp3/internal/spdy/hpackjson/Case.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.spdy.hpackjson;
17 |
18 | import java.util.ArrayList;
19 | import java.util.LinkedHashMap;
20 | import java.util.List;
21 | import java.util.Map;
22 | import okhttp3.internal.framed.Header;
23 | import okio.ByteString;
24 |
25 | /**
26 | * Representation of an individual case (set of headers and wire format). There are many cases for a
27 | * single story. This class is used reflectively with Gson to parse stories.
28 | */
29 | public class Case implements Cloneable {
30 |
31 | private int seqno;
32 | private String wire;
33 | private List