├── 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> headers; 34 | 35 | public List

getHeaders() { 36 | List
result = new ArrayList<>(); 37 | for (Map inputHeader : headers) { 38 | Map.Entry entry = inputHeader.entrySet().iterator().next(); 39 | result.add(new Header(entry.getKey(), entry.getValue())); 40 | } 41 | return result; 42 | } 43 | 44 | public ByteString getWire() { 45 | return ByteString.decodeHex(wire); 46 | } 47 | 48 | public int getSeqno() { 49 | return seqno; 50 | } 51 | 52 | public void setWire(ByteString wire) { 53 | this.wire = wire.hex(); 54 | } 55 | 56 | @Override 57 | protected Case clone() throws CloneNotSupportedException { 58 | Case result = new Case(); 59 | result.seqno = seqno; 60 | result.wire = wire; 61 | result.headers = new ArrayList<>(); 62 | for (Map header : headers) { 63 | result.headers.add(new LinkedHashMap(header)); 64 | } 65 | return result; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /website/static/html5shiv.min.js: -------------------------------------------------------------------------------- 1 | /* 2 | HTML5 Shiv v3.6.2pre | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed 3 | */ 4 | (function(l,f){function m(){var a=e.elements;return"string"==typeof a?a.split(" "):a}function i(a){var b=n[a[o]];b||(b={},h++,a[o]=h,n[h]=b);return b}function p(a,b,c){b||(b=f);if(g)return b.createElement(a);c||(c=i(b));b=c.cache[a]?c.cache[a].cloneNode():r.test(a)?(c.cache[a]=c.createElem(a)).cloneNode():c.createElem(a);return b.canHaveChildren&&!s.test(a)?c.frag.appendChild(b):b}function t(a,b){if(!b.cache)b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag(); 5 | a.createElement=function(c){return!e.shivMethods?b.createElem(c):p(c,a,b)};a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+m().join().replace(/\w+/g,function(a){b.createElem(a);b.frag.createElement(a);return'c("'+a+'")'})+");return n}")(e,b.frag)}function q(a){a||(a=f);var b=i(a);if(e.shivCSS&&!j&&!b.hasCSS){var c,d=a;c=d.createElement("p");d=d.getElementsByTagName("head")[0]||d.documentElement;c.innerHTML="x"; 6 | c=d.insertBefore(c.lastChild,d.firstChild);b.hasCSS=!!c}g||t(a,b);return a}var k=l.html5||{},s=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,r=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,j,o="_html5shiv",h=0,n={},g;(function(){try{var a=f.createElement("a");a.innerHTML="";j="hidden"in a;var b;if(!(b=1==a.childNodes.length)){f.createElement("a");var c=f.createDocumentFragment();b="undefined"==typeof c.cloneNode|| 7 | "undefined"==typeof c.createDocumentFragment||"undefined"==typeof c.createElement}g=b}catch(d){g=j=!0}})();var e={elements:k.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",version:"3.6.2pre",shivCSS:!1!==k.shivCSS,supportsUnknownElements:g,shivMethods:!1!==k.shivMethods,type:"default",shivDocument:q,createElement:p,createDocumentFragment:function(a,b){a||(a=f);if(g)return a.createDocumentFragment(); 8 | for(var b=b||i(a),c=b.frag.cloneNode(),d=0,e=m(),h=e.length;d Integer.MAX_VALUE) { 55 | return Integer.MAX_VALUE; 56 | } else if (seconds < 0) { 57 | return 0; 58 | } else { 59 | return (int) seconds; 60 | } 61 | } catch (NumberFormatException e) { 62 | return defaultValue; 63 | } 64 | } 65 | 66 | private HeaderParser() { 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /okhttp/src/main/java/okhttp3/internal/http/HttpStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package okhttp3.internal.http; 18 | 19 | import java.io.IOException; 20 | import okhttp3.Request; 21 | import okhttp3.Response; 22 | import okhttp3.ResponseBody; 23 | import okio.Sink; 24 | 25 | public interface HttpStream { 26 | /** 27 | * The timeout to use while discarding a stream of input data. Since this is used for connection 28 | * reuse, this timeout should be significantly less than the time it takes to establish a new 29 | * connection. 30 | */ 31 | int DISCARD_STREAM_TIMEOUT_MILLIS = 100; 32 | 33 | /** Returns an output stream where the request body can be streamed. */ 34 | Sink createRequestBody(Request request, long contentLength) throws IOException; 35 | 36 | /** This should update the HTTP engine's sentRequestMillis field. */ 37 | void writeRequestHeaders(Request request) throws IOException; 38 | 39 | /** 40 | * Sends the request body returned by {@link #createRequestBody} to the remote peer. 41 | */ 42 | void writeRequestBody(RetryableSink requestBody) throws IOException; 43 | 44 | /** Flush the request to the underlying socket. */ 45 | void finishRequest() throws IOException; 46 | 47 | /** Read and return response headers. */ 48 | Response.Builder readResponseHeaders() throws IOException; 49 | 50 | /** Returns a stream that reads the response body. */ 51 | ResponseBody openResponseBody(Response response) throws IOException; 52 | 53 | void setHttpEngine(HttpEngine httpEngine); 54 | 55 | /** 56 | * Cancel this stream. Resources held by this stream will be cleaned up, though not synchronously. 57 | * That may happen later by the connection pool thread. 58 | */ 59 | void cancel(); 60 | } 61 | -------------------------------------------------------------------------------- /okhttp-tests/src/test/java/okhttp3/AddressTest.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.List; 19 | import javax.net.SocketFactory; 20 | import okhttp3.internal.Util; 21 | import okhttp3.internal.http.RecordingProxySelector; 22 | import org.junit.Test; 23 | 24 | import static org.junit.Assert.assertEquals; 25 | import static org.junit.Assert.assertFalse; 26 | 27 | public final class AddressTest { 28 | private Dns dns = Dns.SYSTEM; 29 | private SocketFactory socketFactory = SocketFactory.getDefault(); 30 | private Authenticator authenticator = Authenticator.NONE; 31 | private List protocols = Util.immutableList(Protocol.HTTP_1_1); 32 | private List connectionSpecs = Util.immutableList(ConnectionSpec.MODERN_TLS); 33 | private RecordingProxySelector proxySelector = new RecordingProxySelector(); 34 | 35 | @Test public void equalsAndHashcode() throws Exception { 36 | Address a = new Address("square.com", 80, dns, socketFactory, null, null, null, 37 | authenticator, null, protocols, connectionSpecs, proxySelector); 38 | Address b = new Address("square.com", 80, dns, socketFactory, null, null, null, 39 | authenticator, null, protocols, connectionSpecs, proxySelector); 40 | assertEquals(a, b); 41 | assertEquals(a.hashCode(), b.hashCode()); 42 | } 43 | 44 | @Test public void differentProxySelectorsAreDifferent() throws Exception { 45 | Address a = new Address("square.com", 80, dns, socketFactory, null, null, null, 46 | authenticator, null, protocols, connectionSpecs, new RecordingProxySelector()); 47 | Address b = new Address("square.com", 80, dns, socketFactory, null, null, null, 48 | authenticator, null, protocols, connectionSpecs, new RecordingProxySelector()); 49 | assertFalse(a.equals(b)); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /samples/guide/src/main/java/okhttp3/recipes/CheckHandshake.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 java.util.Collections; 21 | import java.util.Set; 22 | import okhttp3.CertificatePinner; 23 | import okhttp3.Interceptor; 24 | import okhttp3.OkHttpClient; 25 | import okhttp3.Request; 26 | import okhttp3.Response; 27 | 28 | public final class CheckHandshake { 29 | /** Rejects otherwise-trusted certificates. */ 30 | private static final Interceptor CHECK_HANDSHAKE_INTERCEPTOR = new Interceptor() { 31 | Set blacklist = Collections.singleton("sha1/DmxUShsZuNiqPQsX2Oi9uv2sCnw="); 32 | 33 | @Override public Response intercept(Chain chain) throws IOException { 34 | for (Certificate certificate : chain.connection().handshake().peerCertificates()) { 35 | String pin = CertificatePinner.pin(certificate); 36 | if (blacklist.contains(pin)) { 37 | throw new IOException("Blacklisted peer certificate: " + pin); 38 | } 39 | } 40 | return chain.proceed(chain.request()); 41 | } 42 | }; 43 | 44 | private final OkHttpClient client = new OkHttpClient.Builder() 45 | .addNetworkInterceptor(CHECK_HANDSHAKE_INTERCEPTOR) 46 | .build(); 47 | 48 | public void run() throws Exception { 49 | Request request = new Request.Builder() 50 | .url("https://publicobject.com/helloworld.txt") 51 | .build(); 52 | 53 | Response response = client.newCall(request).execute(); 54 | if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); 55 | 56 | System.out.println(response.body().string()); 57 | } 58 | 59 | public static void main(String... args) throws Exception { 60 | new CheckHandshake().run(); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /okhttp-tests/src/test/java/okhttp3/internal/framed/BaseTestHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 Square, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package okhttp3.internal.framed; 17 | 18 | import java.io.IOException; 19 | import java.util.List; 20 | import okio.BufferedSource; 21 | import okio.ByteString; 22 | 23 | import static org.junit.Assert.fail; 24 | 25 | class BaseTestHandler implements FrameReader.Handler { 26 | @Override public void data(boolean inFinished, int streamId, BufferedSource source, int length) 27 | throws IOException { 28 | fail(); 29 | } 30 | 31 | @Override 32 | public void headers(boolean outFinished, boolean inFinished, int streamId, int associatedStreamId, 33 | List
headerBlock, HeadersMode headersMode) { 34 | fail(); 35 | } 36 | 37 | @Override public void rstStream(int streamId, ErrorCode errorCode) { 38 | fail(); 39 | } 40 | 41 | @Override public void settings(boolean clearPrevious, Settings settings) { 42 | fail(); 43 | } 44 | 45 | @Override public void ackSettings() { 46 | fail(); 47 | } 48 | 49 | @Override public void ping(boolean ack, int payload1, int payload2) { 50 | fail(); 51 | } 52 | 53 | @Override public void goAway(int lastGoodStreamId, ErrorCode errorCode, ByteString debugData) { 54 | fail(); 55 | } 56 | 57 | @Override public void windowUpdate(int streamId, long windowSizeIncrement) { 58 | fail(); 59 | } 60 | 61 | @Override public void priority(int streamId, int streamDependency, int weight, 62 | boolean exclusive) { 63 | fail(); 64 | } 65 | 66 | @Override 67 | public void pushPromise(int streamId, int associatedStreamId, List
headerBlock) { 68 | fail(); 69 | } 70 | 71 | @Override public void alternateService(int streamId, String origin, ByteString protocol, 72 | String host, int port, long maxAge) { 73 | fail(); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /samples/guide/src/main/java/okhttp3/recipes/PostStreaming.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 | import okio.BufferedSink; 25 | 26 | public final class PostStreaming { 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 | RequestBody requestBody = new RequestBody() { 34 | @Override public MediaType contentType() { 35 | return MEDIA_TYPE_MARKDOWN; 36 | } 37 | 38 | @Override public void writeTo(BufferedSink sink) throws IOException { 39 | sink.writeUtf8("Numbers\n"); 40 | sink.writeUtf8("-------\n"); 41 | for (int i = 2; i <= 997; i++) { 42 | sink.writeUtf8(String.format(" * %s = %s\n", i, factor(i))); 43 | } 44 | } 45 | 46 | private String factor(int n) { 47 | for (int i = 2; i < n; i++) { 48 | int x = n / i; 49 | if (x * i == n) return factor(x) + " × " + i; 50 | } 51 | return Integer.toString(n); 52 | } 53 | }; 54 | 55 | Request request = new Request.Builder() 56 | .url("https://api.github.com/markdown/raw") 57 | .post(requestBody) 58 | .build(); 59 | 60 | Response response = client.newCall(request).execute(); 61 | if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); 62 | 63 | System.out.println(response.body().string()); 64 | } 65 | 66 | public static void main(String... args) throws Exception { 67 | new PostStreaming().run(); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /okhttp-tests/src/test/java/okhttp3/DelegatingServerSocketFactory.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.InetAddress; 20 | import java.net.ServerSocket; 21 | import javax.net.ServerSocketFactory; 22 | 23 | /** 24 | * A {@link ServerSocketFactory} that delegates calls. Sockets can be configured after creation by 25 | * overriding {@link #configureServerSocket(java.net.ServerSocket)}. 26 | */ 27 | public class DelegatingServerSocketFactory extends ServerSocketFactory { 28 | 29 | private final ServerSocketFactory delegate; 30 | 31 | public DelegatingServerSocketFactory(ServerSocketFactory delegate) { 32 | this.delegate = delegate; 33 | } 34 | 35 | @Override 36 | public ServerSocket createServerSocket() throws IOException { 37 | ServerSocket serverSocket = delegate.createServerSocket(); 38 | return configureServerSocket(serverSocket); 39 | } 40 | 41 | @Override 42 | public ServerSocket createServerSocket(int port) throws IOException { 43 | ServerSocket serverSocket = delegate.createServerSocket(port); 44 | return configureServerSocket(serverSocket); 45 | } 46 | 47 | @Override 48 | public ServerSocket createServerSocket(int port, int backlog) throws IOException { 49 | ServerSocket serverSocket = delegate.createServerSocket(port, backlog); 50 | return configureServerSocket(serverSocket); 51 | } 52 | 53 | @Override 54 | public ServerSocket createServerSocket(int port, int backlog, InetAddress ifAddress) 55 | throws IOException { 56 | ServerSocket serverSocket = delegate.createServerSocket(port, backlog, ifAddress); 57 | return configureServerSocket(serverSocket); 58 | } 59 | 60 | protected ServerSocket configureServerSocket(ServerSocket serverSocket) throws IOException { 61 | // No-op by default. 62 | return serverSocket; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /mockwebserver/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 | mockwebserver 13 | MockWebServer 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 | ${project.groupId} 29 | okhttp-ws 30 | ${project.version} 31 | 32 | 33 | org.bouncycastle 34 | bcprov-jdk15on 35 | 36 | 37 | junit 38 | junit 39 | 40 | 41 | 42 | 43 | 44 | 45 | org.apache.maven.plugins 46 | maven-javadoc-plugin 47 | 48 | 49 | http://square.github.io/okhttp/javadoc/ 50 | http://square.github.io/okio/ 51 | 52 | 53 | 54 | 55 | org.apache.maven.plugins 56 | maven-assembly-plugin 57 | 58 | 59 | jar-with-dependencies 60 | 61 | 62 | 63 | 64 | package 65 | 66 | single 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /samples/guide/src/main/java/okhttp3/recipes/PostMultipart.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.MultipartBody; 22 | import okhttp3.OkHttpClient; 23 | import okhttp3.Request; 24 | import okhttp3.RequestBody; 25 | import okhttp3.Response; 26 | 27 | public final class PostMultipart { 28 | /** 29 | * The imgur client ID for OkHttp recipes. If you're using imgur for anything other than running 30 | * these examples, please request your own client ID! https://api.imgur.com/oauth2 31 | */ 32 | private static final String IMGUR_CLIENT_ID = "9199fdef135c122"; 33 | private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png"); 34 | 35 | private final OkHttpClient client = new OkHttpClient(); 36 | 37 | public void run() throws Exception { 38 | // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image 39 | RequestBody requestBody = new MultipartBody.Builder() 40 | .setType(MultipartBody.FORM) 41 | .addFormDataPart("title", "Square Logo") 42 | .addFormDataPart("image", "logo-square.png", 43 | RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png"))) 44 | .build(); 45 | 46 | Request request = new Request.Builder() 47 | .header("Authorization", "Client-ID " + IMGUR_CLIENT_ID) 48 | .url("https://api.imgur.com/3/image") 49 | .post(requestBody) 50 | .build(); 51 | 52 | Response response = client.newCall(request).execute(); 53 | if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); 54 | 55 | System.out.println(response.body().string()); 56 | } 57 | 58 | public static void main(String... args) throws Exception { 59 | new PostMultipart().run(); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /samples/guide/src/main/java/okhttp3/recipes/CancelCall.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.Executors; 20 | import java.util.concurrent.ScheduledExecutorService; 21 | import java.util.concurrent.TimeUnit; 22 | import okhttp3.Call; 23 | import okhttp3.OkHttpClient; 24 | import okhttp3.Request; 25 | import okhttp3.Response; 26 | 27 | public class CancelCall { 28 | private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); 29 | private final OkHttpClient client = new OkHttpClient(); 30 | 31 | public void run() throws Exception { 32 | Request request = new Request.Builder() 33 | .url("http://httpbin.org/delay/2") // This URL is served with a 2 second delay. 34 | .build(); 35 | 36 | final long startNanos = System.nanoTime(); 37 | final Call call = client.newCall(request); 38 | 39 | // Schedule a job to cancel the call in 1 second. 40 | executor.schedule(new Runnable() { 41 | @Override public void run() { 42 | System.out.printf("%.2f Canceling call.%n", (System.nanoTime() - startNanos) / 1e9f); 43 | call.cancel(); 44 | System.out.printf("%.2f Canceled call.%n", (System.nanoTime() - startNanos) / 1e9f); 45 | } 46 | }, 1, TimeUnit.SECONDS); 47 | 48 | try { 49 | System.out.printf("%.2f Executing call.%n", (System.nanoTime() - startNanos) / 1e9f); 50 | Response response = call.execute(); 51 | System.out.printf("%.2f Call was expected to fail, but completed: %s%n", 52 | (System.nanoTime() - startNanos) / 1e9f, response); 53 | } catch (IOException e) { 54 | System.out.printf("%.2f Call failed as expected: %s%n", 55 | (System.nanoTime() - startNanos) / 1e9f, e); 56 | } 57 | } 58 | 59 | public static void main(String... args) throws Exception { 60 | new CancelCall().run(); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /okhttp-ws-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-ws-tests 13 | OkHttp Web Socket Tests 14 | 15 | 16 | 17 | ${project.groupId} 18 | okhttp-ws 19 | ${project.version} 20 | 21 | 22 | 23 | ${project.groupId} 24 | okhttp-testing-support 25 | ${project.version} 26 | test 27 | 28 | 29 | 30 | junit 31 | junit 32 | test 33 | 34 | 35 | ${project.groupId} 36 | mockwebserver 37 | ${project.version} 38 | test 39 | 40 | 41 | 42 | 43 | 44 | 45 | org.apache.maven.plugins 46 | maven-assembly-plugin 47 | 48 | 49 | jar-with-dependencies 50 | 51 | 52 | 53 | okhttp3.ws.AutobahnTester 54 | 55 | 56 | 57 | 58 | 59 | package 60 | 61 | single 62 | 63 | 64 | 65 | 66 | 67 | 68 | org.apache.maven.plugins 69 | maven-deploy-plugin 70 | 71 | true 72 | 73 | 74 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /okhttp-tests/src/test/java/okhttp3/FallbackTestClientSocketFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 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.util.ArrayList; 20 | import java.util.List; 21 | import javax.net.ssl.SSLSocket; 22 | import javax.net.ssl.SSLSocketFactory; 23 | 24 | /** 25 | * An SSLSocketFactory that delegates calls. Sockets created by the delegate are wrapped with ones 26 | * that will not accept the {@link #TLS_FALLBACK_SCSV} cipher, thus bypassing server-side fallback 27 | * checks on platforms that support it. Unfortunately this wrapping will disable any 28 | * reflection-based calls to SSLSocket from Platform. 29 | */ 30 | public class FallbackTestClientSocketFactory extends DelegatingSSLSocketFactory { 31 | /** 32 | * The cipher suite used during TLS connection fallback to indicate a fallback. See 33 | * https://tools.ietf.org/html/draft-ietf-tls-downgrade-scsv-00 34 | */ 35 | public static final String TLS_FALLBACK_SCSV = "TLS_FALLBACK_SCSV"; 36 | 37 | public FallbackTestClientSocketFactory(SSLSocketFactory delegate) { 38 | super(delegate); 39 | } 40 | 41 | @Override protected SSLSocket configureSocket(SSLSocket sslSocket) throws IOException { 42 | return new TlsFallbackScsvDisabledSSLSocket(sslSocket); 43 | } 44 | 45 | private static class TlsFallbackScsvDisabledSSLSocket extends DelegatingSSLSocket { 46 | 47 | public TlsFallbackScsvDisabledSSLSocket(SSLSocket socket) { 48 | super(socket); 49 | } 50 | 51 | @Override public void setEnabledCipherSuites(String[] suites) { 52 | List enabledCipherSuites = new ArrayList(suites.length); 53 | for (String suite : suites) { 54 | if (!suite.equals(TLS_FALLBACK_SCSV)) { 55 | enabledCipherSuites.add(suite); 56 | } 57 | } 58 | delegate.setEnabledCipherSuites( 59 | enabledCipherSuites.toArray(new String[enabledCipherSuites.size()])); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /okhttp-tests/src/test/java/okhttp3/internal/http/ExternalHttp2Example.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2009 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package okhttp3.internal.http; 18 | 19 | import java.io.BufferedReader; 20 | import java.io.InputStreamReader; 21 | import java.net.URL; 22 | import java.util.List; 23 | import javax.net.ssl.HostnameVerifier; 24 | import javax.net.ssl.HttpsURLConnection; 25 | import javax.net.ssl.SSLSession; 26 | import okhttp3.OkHttpClient; 27 | import okhttp3.OkUrlFactory; 28 | import okhttp3.Protocol; 29 | import okhttp3.internal.Util; 30 | 31 | import static okhttp3.internal.http.OkHeaders.SELECTED_PROTOCOL; 32 | 33 | public final class ExternalHttp2Example { 34 | public static void main(String[] args) throws Exception { 35 | URL url = new URL("https://twitter.com"); 36 | OkHttpClient client = new OkHttpClient.Builder() 37 | .protocols(Util.immutableList(Protocol.HTTP_2, Protocol.HTTP_1_1)) 38 | .build(); 39 | HttpsURLConnection connection = (HttpsURLConnection) new OkUrlFactory(client) 40 | .open(url); 41 | 42 | connection.setHostnameVerifier(new HostnameVerifier() { 43 | @Override public boolean verify(String s, SSLSession sslSession) { 44 | System.out.println("VERIFYING " + s); 45 | return true; 46 | } 47 | }); 48 | 49 | int responseCode = connection.getResponseCode(); 50 | System.out.println(responseCode); 51 | List protocolValues = connection.getHeaderFields().get(SELECTED_PROTOCOL); 52 | // If null, probably you didn't add jetty's alpn jar to your boot classpath! 53 | if (protocolValues != null && !protocolValues.isEmpty()) { 54 | System.out.println("PROTOCOL " + protocolValues.get(0)); 55 | } 56 | 57 | BufferedReader reader = 58 | new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); 59 | String line; 60 | while ((line = reader.readLine()) != null) { 61 | System.out.println(line); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /okhttp-tests/src/test/java/okhttp3/internal/http/ExternalSpdyExample.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2009 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package okhttp3.internal.http; 18 | 19 | import java.io.BufferedReader; 20 | import java.io.InputStreamReader; 21 | import java.net.URL; 22 | import java.util.List; 23 | import javax.net.ssl.HostnameVerifier; 24 | import javax.net.ssl.HttpsURLConnection; 25 | import javax.net.ssl.SSLSession; 26 | import okhttp3.OkHttpClient; 27 | import okhttp3.OkUrlFactory; 28 | import okhttp3.Protocol; 29 | import okhttp3.internal.Util; 30 | 31 | import static okhttp3.internal.http.OkHeaders.SELECTED_PROTOCOL; 32 | 33 | public final class ExternalSpdyExample { 34 | public static void main(String[] args) throws Exception { 35 | URL url = new URL("https://www.google.ca/"); 36 | OkHttpClient client = new OkHttpClient.Builder() 37 | .protocols(Util.immutableList(Protocol.SPDY_3, Protocol.HTTP_1_1)) 38 | .build(); 39 | HttpsURLConnection connection = (HttpsURLConnection) new OkUrlFactory(client) 40 | .open(url); 41 | 42 | connection.setHostnameVerifier(new HostnameVerifier() { 43 | @Override public boolean verify(String s, SSLSession sslSession) { 44 | System.out.println("VERIFYING " + s); 45 | return true; 46 | } 47 | }); 48 | 49 | int responseCode = connection.getResponseCode(); 50 | System.out.println(responseCode); 51 | List protocolValues = connection.getHeaderFields().get(SELECTED_PROTOCOL); 52 | // If null, probably you didn't add jetty's alpn jar to your boot classpath! 53 | if (protocolValues != null && !protocolValues.isEmpty()) { 54 | System.out.println("PROTOCOL " + protocolValues.get(0)); 55 | } 56 | 57 | BufferedReader reader = 58 | new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); 59 | String line; 60 | while ((line = reader.readLine()) != null) { 61 | System.out.println(line); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /okhttp-tests/src/test/java/okhttp3/RecordingCallback.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 Square, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package okhttp3; 17 | 18 | import java.io.IOException; 19 | import java.util.ArrayList; 20 | import java.util.Iterator; 21 | import java.util.List; 22 | import java.util.concurrent.TimeUnit; 23 | 24 | /** 25 | * Records received HTTP responses so they can be later retrieved by tests. 26 | */ 27 | public class RecordingCallback implements Callback { 28 | public static final long TIMEOUT_MILLIS = TimeUnit.SECONDS.toMillis(10); 29 | 30 | private final List responses = new ArrayList<>(); 31 | 32 | @Override public synchronized void onFailure(Call call, IOException e) { 33 | responses.add(new RecordedResponse(call.request(), null, null, null, e)); 34 | notifyAll(); 35 | } 36 | 37 | @Override public synchronized void onResponse(Call call, Response response) throws IOException { 38 | String body = response.body().string(); 39 | responses.add(new RecordedResponse(call.request(), response, null, body, null)); 40 | notifyAll(); 41 | } 42 | 43 | /** 44 | * Returns the recorded response triggered by {@code request}. Throws if the response isn't 45 | * enqueued before the timeout. 46 | */ 47 | public synchronized RecordedResponse await(HttpUrl url) throws Exception { 48 | long timeoutMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) + TIMEOUT_MILLIS; 49 | while (true) { 50 | for (Iterator i = responses.iterator(); i.hasNext(); ) { 51 | RecordedResponse recordedResponse = i.next(); 52 | if (recordedResponse.request.url().equals(url)) { 53 | i.remove(); 54 | return recordedResponse; 55 | } 56 | } 57 | 58 | long nowMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); 59 | if (nowMillis >= timeoutMillis) break; 60 | wait(timeoutMillis - nowMillis); 61 | } 62 | 63 | throw new AssertionError("Timed out waiting for response to " + url); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /website/static/jquery.smooth-scroll.min.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * Smooth Scroll - v1.4.10 - 2013-03-02 3 | * https://github.com/kswedberg/jquery-smooth-scroll 4 | * Copyright (c) 2013 Karl Swedberg 5 | * Licensed MIT (https://github.com/kswedberg/jquery-smooth-scroll/blob/master/LICENSE-MIT) 6 | */ 7 | (function(l){function t(l){return l.replace(/(:|\.)/g,"\\$1")}var e="1.4.10",o={exclude:[],excludeWithin:[],offset:0,direction:"top",scrollElement:null,scrollTarget:null,beforeScroll:function(){},afterScroll:function(){},easing:"swing",speed:400,autoCoefficent:2},r=function(t){var e=[],o=!1,r=t.dir&&"left"==t.dir?"scrollLeft":"scrollTop";return this.each(function(){if(this!=document&&this!=window){var t=l(this);t[r]()>0?e.push(this):(t[r](1),o=t[r]()>0,o&&e.push(this),t[r](0))}}),e.length||this.each(function(){"BODY"===this.nodeName&&(e=[this])}),"first"===t.el&&e.length>1&&(e=[e[0]]),e};l.fn.extend({scrollable:function(l){var t=r.call(this,{dir:l});return this.pushStack(t)},firstScrollable:function(l){var t=r.call(this,{el:"first",dir:l});return this.pushStack(t)},smoothScroll:function(e){e=e||{};var o=l.extend({},l.fn.smoothScroll.defaults,e),r=l.smoothScroll.filterPath(location.pathname);return this.unbind("click.smoothscroll").bind("click.smoothscroll",function(e){var n=this,s=l(this),c=o.exclude,i=o.excludeWithin,a=0,f=0,h=!0,u={},d=location.hostname===n.hostname||!n.hostname,m=o.scrollTarget||(l.smoothScroll.filterPath(n.pathname)||r)===r,p=t(n.hash);if(o.scrollTarget||d&&m&&p){for(;h&&c.length>a;)s.is(t(c[a++]))&&(h=!1);for(;h&&i.length>f;)s.closest(i[f++]).length&&(h=!1)}else h=!1;h&&(e.preventDefault(),l.extend(u,o,{scrollTarget:o.scrollTarget||p,link:n}),l.smoothScroll(u))}),this}}),l.smoothScroll=function(t,e){var o,r,n,s,c=0,i="offset",a="scrollTop",f={},h={};"number"==typeof t?(o=l.fn.smoothScroll.defaults,n=t):(o=l.extend({},l.fn.smoothScroll.defaults,t||{}),o.scrollElement&&(i="position","static"==o.scrollElement.css("position")&&o.scrollElement.css("position","relative"))),o=l.extend({link:null},o),a="left"==o.direction?"scrollLeft":a,o.scrollElement?(r=o.scrollElement,c=r[a]()):r=l("html, body").firstScrollable(),o.beforeScroll.call(r,o),n="number"==typeof t?t:e||l(o.scrollTarget)[i]()&&l(o.scrollTarget)[i]()[o.direction]||0,f[a]=n+c+o.offset,s=o.speed,"auto"===s&&(s=f[a]||r.scrollTop(),s/=o.autoCoefficent),h={duration:s,easing:o.easing,complete:function(){o.afterScroll.call(o.link,o)}},o.step&&(h.step=o.step),r.length?r.stop().animate(f,h):o.afterScroll.call(o.link,o)},l.smoothScroll.version=e,l.smoothScroll.filterPath=function(l){return l.replace(/^\//,"").replace(/(index|default).[a-zA-Z]{3,4}$/,"").replace(/\/$/,"")},l.fn.smoothScroll.defaults=o})(jQuery); -------------------------------------------------------------------------------- /samples/guide/src/main/java/okhttp3/guide/PriorityExample.java: -------------------------------------------------------------------------------- 1 | package okhttp3.guide; 2 | 3 | import okhttp3.*; 4 | 5 | import java.io.IOException; 6 | 7 | /** 8 | * Created by lizhangqu on 16/1/17. 9 | */ 10 | public class PriorityExample { 11 | private static OkHttpClient okHttpClient = new OkHttpClient(); 12 | private static Callback callback = new Callback() { 13 | @Override 14 | public void onFailure(Call call, IOException e) { 15 | e.printStackTrace(); 16 | } 17 | 18 | @Override 19 | public void onResponse(Call call, Response response) throws IOException { 20 | System.out.println(response.request().priority() + "===" + response); 21 | } 22 | }; 23 | 24 | public static void main(String[] args) { 25 | Request.Builder builder1 = new Request.Builder(); 26 | Request request0 = builder1.url("https://www.baidu.com").build(); 27 | 28 | Request request1 = request0.newBuilder().priority(14).build(); 29 | Request request2 = request0.newBuilder().priority(2).build(); 30 | Request request3 = request0.newBuilder().priority(40).build(); 31 | Request request4 = request0.newBuilder().priority(20).build(); 32 | Request request5 = request0.newBuilder().priority(30).build(); 33 | Request request6 = request0.newBuilder().priority(10).build(); 34 | Request request7 = request0.newBuilder().priority(5).build(); 35 | Request request8 = request0.newBuilder().priority(34).build(); 36 | Request request9 = request0.newBuilder().priority(100).build(); 37 | Request request10 = request0.newBuilder().priority(500).build(); 38 | 39 | 40 | Call call1= okHttpClient.newCall(request1); 41 | Call call2= okHttpClient.newCall(request2); 42 | Call call3= okHttpClient.newCall(request3); 43 | Call call4= okHttpClient.newCall(request4); 44 | Call call5= okHttpClient.newCall(request5); 45 | Call call6= okHttpClient.newCall(request6); 46 | Call call7= okHttpClient.newCall(request7); 47 | Call call8= okHttpClient.newCall(request8); 48 | Call call9= okHttpClient.newCall(request9); 49 | Call call10= okHttpClient.newCall(request10); 50 | 51 | 52 | call1.enqueue(callback); 53 | call2.enqueue(callback); 54 | call3.enqueue(callback); 55 | call4.enqueue(callback); 56 | call5.enqueue(callback); 57 | call6.enqueue(callback); 58 | call7.enqueue(callback); 59 | call8.enqueue(callback); 60 | call9.enqueue(callback); 61 | call10.enqueue(callback); 62 | 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /okhttp-tests/src/test/java/okhttp3/DelegatingSocketFactory.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.InetAddress; 20 | import java.net.Socket; 21 | import java.net.UnknownHostException; 22 | import javax.net.SocketFactory; 23 | 24 | /** 25 | * A {@link SocketFactory} that delegates calls. Sockets can be configured after creation by 26 | * overriding {@link #configureSocket(java.net.Socket)}. 27 | */ 28 | public class DelegatingSocketFactory extends SocketFactory { 29 | 30 | private final SocketFactory delegate; 31 | 32 | public DelegatingSocketFactory(SocketFactory delegate) { 33 | this.delegate = delegate; 34 | } 35 | 36 | @Override 37 | public Socket createSocket() throws IOException { 38 | Socket socket = delegate.createSocket(); 39 | return configureSocket(socket); 40 | } 41 | 42 | @Override 43 | public Socket createSocket(String host, int port) throws IOException, UnknownHostException { 44 | Socket socket = delegate.createSocket(host, port); 45 | return configureSocket(socket); 46 | } 47 | 48 | @Override 49 | public Socket createSocket(String host, int port, InetAddress localAddress, int localPort) 50 | throws IOException, UnknownHostException { 51 | Socket socket = delegate.createSocket(host, port, localAddress, localPort); 52 | return configureSocket(socket); 53 | } 54 | 55 | @Override 56 | public Socket createSocket(InetAddress host, int port) throws IOException { 57 | Socket socket = delegate.createSocket(host, port); 58 | return configureSocket(socket); 59 | } 60 | 61 | @Override 62 | public Socket createSocket(InetAddress host, int port, InetAddress localAddress, int localPort) 63 | throws IOException { 64 | Socket socket = delegate.createSocket(host, port, localAddress, localPort); 65 | return configureSocket(socket); 66 | } 67 | 68 | protected Socket configureSocket(Socket socket) throws IOException { 69 | // No-op by default. 70 | return socket; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /samples/guide/src/main/java/okhttp3/recipes/CacheResponse.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.Cache; 21 | import okhttp3.OkHttpClient; 22 | import okhttp3.Request; 23 | import okhttp3.Response; 24 | 25 | public final class CacheResponse { 26 | private final OkHttpClient client; 27 | 28 | public CacheResponse(File cacheDirectory) throws Exception { 29 | int cacheSize = 10 * 1024 * 1024; // 10 MiB 30 | Cache cache = new Cache(cacheDirectory, cacheSize); 31 | 32 | client = new OkHttpClient.Builder() 33 | .cache(cache) 34 | .build(); 35 | } 36 | 37 | public void run() throws Exception { 38 | Request request = new Request.Builder() 39 | .url("http://publicobject.com/helloworld.txt") 40 | .build(); 41 | 42 | Response response1 = client.newCall(request).execute(); 43 | if (!response1.isSuccessful()) throw new IOException("Unexpected code " + response1); 44 | 45 | String response1Body = response1.body().string(); 46 | System.out.println("Response 1 response: " + response1); 47 | System.out.println("Response 1 cache response: " + response1.cacheResponse()); 48 | System.out.println("Response 1 network response: " + response1.networkResponse()); 49 | 50 | Response response2 = client.newCall(request).execute(); 51 | if (!response2.isSuccessful()) throw new IOException("Unexpected code " + response2); 52 | 53 | String response2Body = response2.body().string(); 54 | System.out.println("Response 2 response: " + response2); 55 | System.out.println("Response 2 cache response: " + response2.cacheResponse()); 56 | System.out.println("Response 2 network response: " + response2.networkResponse()); 57 | 58 | System.out.println("Response 2 equals Response 1? " + response1Body.equals(response2Body)); 59 | } 60 | 61 | public static void main(String... args) throws Exception { 62 | new CacheResponse(new File("CacheResponse.tmp")).run(); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /okhttp/src/main/java/okhttp3/Authenticator.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.io.IOException; 19 | 20 | /** 21 | * Responds to an authentication challenge from either a remote web server or a proxy server. 22 | * Implementations may either attempt to satisfy the challenge by returning a request that includes 23 | * an authorization header, or they may refuse the challenge by returning null. In this case the 24 | * unauthenticated response will be returned to the caller that triggered it. 25 | * 26 | *

When authentication is requested by an origin server, the response code is 401 and the 27 | * implementation should respond with a new request that sets the "Authorization" header. 28 | *

   {@code
29 |  *
30 |  *    String credential = Credentials.basic(...)
31 |  *    return response.request().newBuilder()
32 |  *        .header("Authorization", credential)
33 |  *        .build();
34 |  * }
35 | * 36 | *

Whn authentication is requested by a proxy server, the response code is 407 and the 37 | * implementation should respond with a new request that sets the "Proxy-Authorization" header. 38 | *

   {@code
39 |  *
40 |  *    String credential = Credentials.basic(...)
41 |  *    return response.request().newBuilder()
42 |  *        .header("Proxy-Authorization", credential)
43 |  *        .build();
44 |  * }
45 | * 46 | *

Applications may configure OkHttp with an authenticator for origin servers, or proxy servers, 47 | * or both. 48 | */ 49 | public interface Authenticator { 50 | /** An authenticator that knows no credentials and makes no attempt to authenticate. */ 51 | Authenticator NONE = new Authenticator() { 52 | @Override public Request authenticate(Route route, Response response) { 53 | return null; 54 | } 55 | }; 56 | 57 | /** 58 | * Returns a request that includes a credential to satisfy an authentication challenge in {@code 59 | * response}. Returns null if the challenge cannot be satisfied. 60 | */ 61 | Request authenticate(Route route, Response response) throws IOException; 62 | } 63 | -------------------------------------------------------------------------------- /samples/guide/src/main/java/okhttp3/recipes/WebSocketEcho.java: -------------------------------------------------------------------------------- 1 | package okhttp3.recipes; 2 | 3 | import java.io.IOException; 4 | import java.util.concurrent.Executor; 5 | import java.util.concurrent.Executors; 6 | import okhttp3.OkHttpClient; 7 | import okhttp3.Request; 8 | import okhttp3.RequestBody; 9 | import okhttp3.Response; 10 | import okhttp3.ResponseBody; 11 | import okhttp3.ws.WebSocket; 12 | import okhttp3.ws.WebSocketCall; 13 | import okhttp3.ws.WebSocketListener; 14 | import okio.Buffer; 15 | import okio.ByteString; 16 | 17 | import static okhttp3.ws.WebSocket.BINARY; 18 | import static okhttp3.ws.WebSocket.TEXT; 19 | 20 | public final class WebSocketEcho implements WebSocketListener { 21 | private final Executor writeExecutor = Executors.newSingleThreadExecutor(); 22 | 23 | private void run() throws IOException { 24 | OkHttpClient client = new OkHttpClient(); 25 | 26 | Request request = new Request.Builder() 27 | .url("ws://echo.websocket.org") 28 | .build(); 29 | WebSocketCall.create(client, request).enqueue(this); 30 | 31 | // Trigger shutdown of the dispatcher's executor so this process can exit cleanly. 32 | client.dispatcher().executorService().shutdown(); 33 | } 34 | 35 | @Override public void onOpen(final WebSocket webSocket, Response response) { 36 | writeExecutor.execute(new Runnable() { 37 | @Override public void run() { 38 | try { 39 | webSocket.sendMessage(RequestBody.create(TEXT, "Hello...")); 40 | webSocket.sendMessage(RequestBody.create(TEXT, "...World!")); 41 | webSocket.sendMessage(RequestBody.create(BINARY, ByteString.decodeHex("deadbeef"))); 42 | webSocket.close(1000, "Goodbye, World!"); 43 | } catch (IOException e) { 44 | System.err.println("Unable to send messages: " + e.getMessage()); 45 | } 46 | } 47 | }); 48 | } 49 | 50 | @Override public void onMessage(ResponseBody message) throws IOException { 51 | if (message.contentType() == TEXT) { 52 | System.out.println("MESSAGE: " + message.string()); 53 | } else { 54 | System.out.println("MESSAGE: " + message.source().readByteString().hex()); 55 | } 56 | message.close(); 57 | } 58 | 59 | @Override public void onPong(Buffer payload) { 60 | System.out.println("PONG: " + payload.readUtf8()); 61 | } 62 | 63 | @Override public void onClose(int code, String reason) { 64 | System.out.println("CLOSE: " + code + " " + reason); 65 | } 66 | 67 | @Override public void onFailure(IOException e, Response response) { 68 | e.printStackTrace(); 69 | } 70 | 71 | public static void main(String... args) throws IOException { 72 | new WebSocketEcho().run(); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /okhttp-urlconnection/src/main/java/okhttp3/internal/JavaNetHeaders.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package okhttp3.internal; 17 | 18 | import java.util.ArrayList; 19 | import java.util.Collections; 20 | import java.util.Comparator; 21 | import java.util.List; 22 | import java.util.Map; 23 | import java.util.TreeMap; 24 | import okhttp3.Headers; 25 | 26 | public final class JavaNetHeaders { 27 | private JavaNetHeaders() { 28 | } 29 | 30 | private static final Comparator FIELD_NAME_COMPARATOR = new Comparator() { 31 | // @FindBugsSuppressWarnings("ES_COMPARING_PARAMETER_STRING_WITH_EQ") 32 | @Override public int compare(String a, String b) { 33 | if (a == b) { 34 | return 0; 35 | } else if (a == null) { 36 | return -1; 37 | } else if (b == null) { 38 | return 1; 39 | } else { 40 | return String.CASE_INSENSITIVE_ORDER.compare(a, b); 41 | } 42 | } 43 | }; 44 | 45 | /** 46 | * Returns an immutable map containing each field to its list of values. 47 | * 48 | * @param valueForNullKey the request line for requests, or the status line for responses. If 49 | * non-null, this value is mapped to the null key. 50 | */ 51 | public static Map> toMultimap(Headers headers, String valueForNullKey) { 52 | Map> result = new TreeMap<>(FIELD_NAME_COMPARATOR); 53 | for (int i = 0, size = headers.size(); i < size; i++) { 54 | String fieldName = headers.name(i); 55 | String value = headers.value(i); 56 | 57 | List allValues = new ArrayList<>(); 58 | List otherValues = result.get(fieldName); 59 | if (otherValues != null) { 60 | allValues.addAll(otherValues); 61 | } 62 | allValues.add(value); 63 | result.put(fieldName, Collections.unmodifiableList(allValues)); 64 | } 65 | if (valueForNullKey != null) { 66 | result.put(null, Collections.unmodifiableList(Collections.singletonList(valueForNullKey))); 67 | } 68 | return Collections.unmodifiableMap(result); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /okhttp/src/main/java/okhttp3/CookieJar.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.Collections; 19 | import java.util.List; 20 | 21 | /** 22 | * Provides policy and persistence for HTTP cookies. 23 | * 24 | *

As policy, implementations of this interface are responsible for selecting which cookies to 25 | * accept and which to reject. A reasonable policy is to reject all cookies, though that may be 26 | * interfere with session-based authentication schemes that require cookies. 27 | * 28 | *

As persistence, implementations of this interface must also provide storage of cookies. Simple 29 | * implementations may store cookies in memory; sophisticated ones may use the file system or 30 | * database to hold accepted cookies. The cookie storage model specifies 32 | * policies for updating and expiring cookies. 33 | */ 34 | public interface CookieJar { 35 | /** A cookie jar that never accepts any cookies. */ 36 | CookieJar NO_COOKIES = new CookieJar() { 37 | @Override public void saveFromResponse(HttpUrl url, List cookies) { 38 | } 39 | 40 | @Override public List loadForRequest(HttpUrl url) { 41 | return Collections.emptyList(); 42 | } 43 | }; 44 | 45 | /** 46 | * Saves {@code cookies} from an HTTP response to this store according to this jar's policy. 47 | * 48 | *

Note that this method may be called a second time for a single HTTP response if the response 49 | * includes a trailer. For this obscure HTTP feature, {@code cookies} contains only the trailer's 50 | * cookies. 51 | */ 52 | void saveFromResponse(HttpUrl url, List cookies); 53 | 54 | /** 55 | * Load cookies from the jar for an HTTP request to {@code url}. This method returns a possibly 56 | * empty list of cookies for the network request. 57 | * 58 | *

Simple implementations will return the accepted cookies that have not yet expired and that 59 | * {@linkplain Cookie#matches match} {@code url}. 60 | */ 61 | List loadForRequest(HttpUrl url); 62 | } 63 | -------------------------------------------------------------------------------- /okhttp/src/main/java/okhttp3/internal/http/RetryableSink.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2010 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package okhttp3.internal.http; 18 | 19 | import java.io.IOException; 20 | import java.net.ProtocolException; 21 | import okio.Buffer; 22 | import okio.Sink; 23 | import okio.Timeout; 24 | 25 | import static okhttp3.internal.Util.checkOffsetAndCount; 26 | 27 | /** 28 | * An HTTP request body that's completely buffered in memory. This allows the post body to be 29 | * transparently re-sent if the HTTP request must be sent multiple times. 30 | */ 31 | public final class RetryableSink implements Sink { 32 | private boolean closed; 33 | private final int limit; 34 | private final Buffer content = new Buffer(); 35 | 36 | public RetryableSink(int limit) { 37 | this.limit = limit; 38 | } 39 | 40 | public RetryableSink() { 41 | this(-1); 42 | } 43 | 44 | @Override public void close() throws IOException { 45 | if (closed) return; 46 | closed = true; 47 | if (content.size() < limit) { 48 | throw new ProtocolException( 49 | "content-length promised " + limit + " bytes, but received " + content.size()); 50 | } 51 | } 52 | 53 | @Override public void write(Buffer source, long byteCount) throws IOException { 54 | if (closed) throw new IllegalStateException("closed"); 55 | checkOffsetAndCount(source.size(), 0, byteCount); 56 | if (limit != -1 && content.size() > limit - byteCount) { 57 | throw new ProtocolException("exceeded content-length limit of " + limit + " bytes"); 58 | } 59 | content.write(source, byteCount); 60 | } 61 | 62 | @Override public void flush() throws IOException { 63 | } 64 | 65 | @Override public Timeout timeout() { 66 | return Timeout.NONE; 67 | } 68 | 69 | public long contentLength() throws IOException { 70 | return content.size(); 71 | } 72 | 73 | public void writeToSocket(Sink socketOut) throws IOException { 74 | // Copy the content; otherwise we won't have data to retry. 75 | Buffer buffer = new Buffer(); 76 | content.copyTo(buffer, 0, content.size()); 77 | socketOut.write(buffer, buffer.size()); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /mockwebserver/src/main/java/okhttp3/mockwebserver/QueueDispatcher.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 | import java.net.HttpURLConnection; 19 | import java.util.concurrent.BlockingQueue; 20 | import java.util.concurrent.LinkedBlockingQueue; 21 | import java.util.logging.Logger; 22 | 23 | /** 24 | * Default dispatcher that processes a script of responses. Populate the script by calling {@link 25 | * #enqueueResponse(MockResponse)}. 26 | */ 27 | public class QueueDispatcher extends Dispatcher { 28 | private static final Logger logger = Logger.getLogger(QueueDispatcher.class.getName()); 29 | protected final BlockingQueue responseQueue = new LinkedBlockingQueue<>(); 30 | private MockResponse failFastResponse; 31 | 32 | @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException { 33 | // To permit interactive/browser testing, ignore requests for favicons. 34 | final String requestLine = request.getRequestLine(); 35 | if (requestLine != null && requestLine.equals("GET /favicon.ico HTTP/1.1")) { 36 | logger.info("served " + requestLine); 37 | return new MockResponse().setResponseCode(HttpURLConnection.HTTP_NOT_FOUND); 38 | } 39 | 40 | if (failFastResponse != null && responseQueue.peek() == null) { 41 | // Fail fast if there's no response queued up. 42 | return failFastResponse; 43 | } 44 | 45 | return responseQueue.take(); 46 | } 47 | 48 | @Override public MockResponse peek() { 49 | MockResponse peek = responseQueue.peek(); 50 | if (peek != null) return peek; 51 | if (failFastResponse != null) return failFastResponse; 52 | return super.peek(); 53 | } 54 | 55 | public void enqueueResponse(MockResponse response) { 56 | responseQueue.add(response); 57 | } 58 | 59 | public void setFailFast(boolean failFast) { 60 | MockResponse failFastResponse = failFast 61 | ? new MockResponse().setResponseCode(HttpURLConnection.HTTP_NOT_FOUND) 62 | : null; 63 | setFailFast(failFastResponse); 64 | } 65 | 66 | public void setFailFast(MockResponse failFastResponse) { 67 | this.failFastResponse = failFastResponse; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /okhttp/src/main/java/okhttp3/internal/framed/ErrorCode.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 Square, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package okhttp3.internal.framed; 17 | 18 | // http://tools.ietf.org/html/draft-ietf-httpbis-http2-17#section-7 19 | public enum ErrorCode { 20 | /** Not an error! For SPDY stream resets, prefer null over NO_ERROR. */ 21 | NO_ERROR(0, -1, 0), 22 | 23 | PROTOCOL_ERROR(1, 1, 1), 24 | 25 | /** A subtype of PROTOCOL_ERROR used by SPDY. */ 26 | INVALID_STREAM(1, 2, -1), 27 | 28 | /** A subtype of PROTOCOL_ERROR used by SPDY. */ 29 | UNSUPPORTED_VERSION(1, 4, -1), 30 | 31 | /** A subtype of PROTOCOL_ERROR used by SPDY. */ 32 | STREAM_IN_USE(1, 8, -1), 33 | 34 | /** A subtype of PROTOCOL_ERROR used by SPDY. */ 35 | STREAM_ALREADY_CLOSED(1, 9, -1), 36 | 37 | INTERNAL_ERROR(2, 6, 2), 38 | 39 | FLOW_CONTROL_ERROR(3, 7, -1), 40 | 41 | STREAM_CLOSED(5, -1, -1), 42 | 43 | FRAME_TOO_LARGE(6, 11, -1), 44 | 45 | REFUSED_STREAM(7, 3, -1), 46 | 47 | CANCEL(8, 5, -1), 48 | 49 | COMPRESSION_ERROR(9, -1, -1), 50 | 51 | CONNECT_ERROR(10, -1, -1), 52 | 53 | ENHANCE_YOUR_CALM(11, -1, -1), 54 | 55 | INADEQUATE_SECURITY(12, -1, -1), 56 | 57 | HTTP_1_1_REQUIRED(13, -1, -1), 58 | 59 | INVALID_CREDENTIALS(-1, 10, -1); 60 | 61 | public final int httpCode; 62 | public final int spdyRstCode; 63 | public final int spdyGoAwayCode; 64 | 65 | private ErrorCode(int httpCode, int spdyRstCode, int spdyGoAwayCode) { 66 | this.httpCode = httpCode; 67 | this.spdyRstCode = spdyRstCode; 68 | this.spdyGoAwayCode = spdyGoAwayCode; 69 | } 70 | 71 | public static ErrorCode fromSpdy3Rst(int code) { 72 | for (ErrorCode errorCode : ErrorCode.values()) { 73 | if (errorCode.spdyRstCode == code) return errorCode; 74 | } 75 | return null; 76 | } 77 | 78 | public static ErrorCode fromHttp2(int code) { 79 | for (ErrorCode errorCode : ErrorCode.values()) { 80 | if (errorCode.httpCode == code) return errorCode; 81 | } 82 | return null; 83 | } 84 | 85 | public static ErrorCode fromSpdyGoAway(int code) { 86 | for (ErrorCode errorCode : ErrorCode.values()) { 87 | if (errorCode.spdyGoAwayCode == code) return errorCode; 88 | } 89 | return null; 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /okhttp-ws/src/main/java/okhttp3/ws/WebSocket.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.ws; 17 | 18 | import java.io.IOException; 19 | import okhttp3.MediaType; 20 | import okhttp3.RequestBody; 21 | import okio.Buffer; 22 | 23 | /** Blocking interface to connect and write to a web socket. */ 24 | public interface WebSocket { 25 | /** A {@link MediaType} indicating UTF-8 text frames should be used when sending the message. */ 26 | MediaType TEXT = MediaType.parse("application/vnd.okhttp.websocket+text; charset=utf-8"); 27 | /** A {@link MediaType} indicating binary frames should be used when sending the message. */ 28 | MediaType BINARY = MediaType.parse("application/vnd.okhttp.websocket+binary"); 29 | 30 | /** 31 | * Send a message payload to the server. 32 | * 33 | *

The {@linkplain RequestBody#contentType() content type} of {@code message} should be either 34 | * {@link #TEXT} or {@link #BINARY}. 35 | * 36 | * @throws IOException if unable to write the message. Clients must call {@link #close} when this 37 | * happens to ensure resources are cleaned up. 38 | * @throws IllegalStateException if not connected, already closed, or another writer is active. 39 | */ 40 | void sendMessage(RequestBody message) throws IOException; 41 | 42 | /** 43 | * Send a ping to the server with optional payload. 44 | * 45 | * @throws IOException if unable to write the ping. Clients must call {@link #close} when this 46 | * happens to ensure resources are cleaned up. 47 | * @throws IllegalStateException if already closed. 48 | */ 49 | void sendPing(Buffer payload) throws IOException; 50 | 51 | /** 52 | * Send a close frame to the server. 53 | * 54 | *

The corresponding {@link WebSocketListener} will continue to get messages until its {@link 55 | * WebSocketListener#onClose onClose()} method is called. 56 | * 57 | *

It is an error to call this method before calling close on an active writer. Calling this 58 | * method more than once has no effect. 59 | * 60 | * @throws IOException if unable to write the close message. Resources will still be freed. 61 | * @throws IllegalStateException if already closed. 62 | */ 63 | void close(int code, String reason) throws IOException; 64 | } 65 | --------------------------------------------------------------------------------