Square’s meticulous HTTP client for the JVM, Android, and GraalVM.

Overview

OkHttp

See the project website for documentation and APIs.

HTTP is the way modern applications network. It’s how we exchange data & media. Doing HTTP efficiently makes your stuff load faster and saves bandwidth.

OkHttp is an HTTP client that’s efficient by default:

  • HTTP/2 support allows all requests to the same host to share a socket.
  • Connection pooling reduces request latency (if HTTP/2 isn’t available).
  • Transparent GZIP shrinks download sizes.
  • Response caching avoids the network completely for repeat requests.

OkHttp perseveres when the network is troublesome: it will silently recover from common connection problems. If your service has multiple IP addresses, OkHttp will attempt alternate addresses if the first connect fails. This is necessary for IPv4+IPv6 and services hosted in redundant data centers. OkHttp supports modern TLS features (TLS 1.3, ALPN, certificate pinning). It can be configured to fall back for broad connectivity.

Using OkHttp is easy. Its request/response API is designed with fluent builders and immutability. It supports both synchronous blocking calls and async calls with callbacks.

Get a URL

This program downloads a URL and prints its contents as a string. Full source.

OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
  Request request = new Request.Builder()
      .url(url)
      .build();

  try (Response response = client.newCall(request).execute()) {
    return response.body().string();
  }
}

Post to a Server

This program posts data to a service. Full source.

public static final MediaType JSON
    = MediaType.get("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(JSON, json);
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  try (Response response = client.newCall(request).execute()) {
    return response.body().string();
  }
}

Further examples are on the OkHttp Recipes page.

Requirements

OkHttp works on Android 5.0+ (API level 21+) and Java 8+.

OkHttp depends on Okio for high-performance I/O and the Kotlin standard library. Both are small libraries with strong backward-compatibility.

We highly recommend you keep OkHttp up-to-date. As with auto-updating web browsers, staying current with HTTPS clients is an important defense against potential security problems. We track the dynamic TLS ecosystem and adjust OkHttp to improve connectivity and security.

OkHttp uses your platform's built-in TLS implementation. On Java platforms OkHttp also supports Conscrypt, which integrates BoringSSL with Java. OkHttp will use Conscrypt if it is the first security provider:

Security.insertProviderAt(Conscrypt.newProvider(), 1);

The OkHttp 3.12.x branch supports Android 2.3+ (API level 9+) and Java 7+. These platforms lack support for TLS 1.2 and should not be used. But because upgrading is difficult, we will backport critical fixes to the 3.12.x branch through December 31, 2021.

Releases

Our change log has release history.

The latest release is available on Maven Central.

implementation("com.squareup.okhttp3:okhttp:4.9.0")

Snapshot builds are available. R8 and ProGuard rules are available.

Also, we have a bill of materials (BOM) available to help you keep OkHttp artifacts up to date and be sure about version compatibility.

    dependencies {
       // define a BOM and its version
       implementation(platform("com.squareup.okhttp3:okhttp-bom:4.9.0"))
       
       // define any required OkHttp artifacts without version
       implementation("com.squareup.okhttp3:okhttp")
       implementation("com.squareup.okhttp3:logging-interceptor")
    }

MockWebServer

OkHttp includes a library for testing HTTP, HTTPS, and HTTP/2 clients.

The latest release is available on Maven Central.

testImplementation("com.squareup.okhttp3:mockwebserver:4.9.0")

GraalVM Native Image

Building your native images with Graal https://www.graalvm.org/ should work automatically. Please report any bugs or workarounds you find.

See the okcurl module for an example build.

$ ./gradlew okcurl:nativeImage
$ ./okcurl/build/graal/okcurl https://httpbin.org/get

License

Copyright 2019 Square, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Comments
  • Analytics API

    Analytics API

    We should add verbose logging for the response cache. Folks occasionally are puzzled when the cache doesn't work. Let's make it easy for them to figure out why.

    It would also be handy for debug panels and optimizers to monitor bytes in and out, connections created, etc.

    enhancement 
    opened by swankjesse 106
  • EOFException in RealBufferedSource.readUtf8LineStrict

    EOFException in RealBufferedSource.readUtf8LineStrict

    A few people have reported this. Needs investigation & fix.

    java.io.EOFException: null
        at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:154) ~[na:0.0]
        at com.squareup.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:189) ~[na:0.0]
        at com.squareup.okhttp.internal.http.HttpTransport.readResponseHeaders(HttpTransport.java:101) ~[na:0.0]
        at com.squareup.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:676) ~[na:0.0]
        at com.squareup.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:426) ~[na:0.0]
        at com.squareup.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:371) ~[na:0.0]
        at com.squareup.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:466) ~[na:0.0]
        at com.squareup.okhttp.internal.huc.DelegatingHttpsURLConnection.getResponseCode(DelegatingHttpsURLConnection.java:105) ~[na:0.0]
    
    bug 
    opened by swankjesse 100
  • EOFException in RealBufferedSource.readUtf8LineStrict(): 0-bytes in stream

    EOFException in RealBufferedSource.readUtf8LineStrict(): 0-bytes in stream

    We're getting an EOF exception with size=0 in the stream.

    java.io.EOFException: \n not found: size=0 content=...
                at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:200)
                at com.squareup.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:187)
                at com.squareup.okhttp.internal.http.HttpTransport.readResponseHeaders(HttpTransport.java:80)
                at com.squareup.okhttp.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:791)
                at com.squareup.okhttp.internal.http.HttpEngine.access$200(HttpEngine.java:90)
    

    (Forked from issue 1114.)

    bug 
    opened by swankjesse 78
  • Unable to extract the trust manager

    Unable to extract the trust manager

    Hi, after upgrading from OkHttp 3.0.1 to 3.1.0 I get the following stack trace and crash after calling build() to create a OkHttpClient.

    java.lang.IllegalStateException: Unable to extract the trust manager on okhttp3.internal.Platform$Android@1d8cf999, sslSocketFactory is class com.google.android.gms.org.conscrypt.KitKatPlatformOpenSSLSocketAdapterFactory
                                                                            at okhttp3.OkHttpClient.<init>(OkHttpClient.java:187)
                                                                            at okhttp3.OkHttpClient.<init>(OkHttpClient.java:60)
                                                                            at okhttp3.OkHttpClient$Builder.build(OkHttpClient.java:719)
    

    This issue was not present in 3.0.1.

    Here's where the crash happens:

    OkHttpClient.Builder builder = new OkHttpClient.Builder()
                        .connectTimeout(10, TimeUnit.SECONDS)
                        .writeTimeout(10, TimeUnit.SECONDS)
                        .readTimeout(30, TimeUnit.SECONDS);
    
                OkHttpClient client = builder.build();
    
    bug 
    opened by AlexLardschneider 72
  • NoSuchElementException in RouteSelector

    NoSuchElementException in RouteSelector

    okhttp 3.7.0 retrofit 2.2.0

    All device brands and Android versions are reporting this issue.

    It happened for example after I tapped a notification, the app then makes a GET which ended in this exception. It didn't happen when I recreated the scenario. Device was Pixel, Android 7.1.2, on WLAN.

    java.util.NoSuchElementException
      at okhttp3.internal.connection.RouteSelector.next(RouteSelector.java:77)
      at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:171)
      at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:121)
      at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:100)
      at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
      at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
      at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
      at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
      at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
      at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
      at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
      at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
      at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:120)
      at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
      at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
      at okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.java:211)
      at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
      at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
      at com.readystatesoftware.chuck.ChuckInterceptor.intercept(ChuckInterceptor.java:167)
      at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
      at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
      at com.myownpackage.manager.OkHttpManager$AuthenticationInterceptor.intercept(OkHttpManager.java:135)
      at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
      at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
      at com.myownpackage.manager.OkHttpManager$NetworkLoggingInterceptor.intercept(OkHttpManager.java:190)
      at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
      at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
      at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:185)
      at okhttp3.RealCall.execute(RealCall.java:69)
      at retrofit2.OkHttpCall.execute(OkHttpCall.java:174)
      at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.execute(ExecutorCallAdapterFactory.java:89)
      at com.myownpackage.ui.ProfileFragment$11.doInBackground(ProfileFragment.java:516)
      at com.myownpackage.ui.ProfileFragment$11.doInBackground(ProfileFragment.java:511)
      at com.nanotasks.AbstractTask.doInBackground(AbstractTask.java:18)
      at com.nanotasks.AbstractTask.doInBackground(AbstractTask.java:7)
      at android.os.AsyncTask$2.call(AsyncTask.java:305)
      at java.util.concurrent.FutureTask.run(FutureTask.java:237)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
      at java.lang.Thread.run(Thread.java:761)
    
    opened by Jeff11 65
  • support enabling TLSv1.2 on Android 4.1-4.4.

    support enabling TLSv1.2 on Android 4.1-4.4.

    Our lawyers and security consultants claim that for PCI compliance*, we must disable TLS 1.0 and 1.1 on our servers. For some confusing reason, Android has supported TLS 1.2 since API 16 (android 4.1) but enabled it by default only since API 20 (android "4.4W").

    With okhttp 2.6, we were able to force use of TLS 1.2 with:

    OkHttpClient cli = new OkHttpClient();
    SSLContext sc = SSLContext.getInstance("TLSv1.2");
    sc.init(null, null, null);
    cli.setSslSocketFactory(new Tls12SocketFactory(sc.getSocketFactory()));
    ConnectionSpec cs = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
            .tlsVersions(TlsVersion.TLS_1_2)
            .build();
    cli.setConnectionSpecs(ImmutableList.of(cs));
    

    where Tls12SocketFactory is this.

    However, okhttp 3.1 uses some kind of reflection on internal implementation details of the SSLSocketFactory, so the above implementation no longer works. And, indeed, it's a bit silly to make callers write so much code anyway. Specifying TLS_1_2 in the ConnectionSpec should be enough to get TLSv1.2 whenever it is supported.

    As far as I can tell, the only reason why the custom socket factory is needed in the first place is that ConnectionSpec.supportedSpec() calls SSLSocket.getEnabledProtocols() to learn the list of protocols supported by the system, so on Android 4.x where TLS 1.2 is supported but not enabled by default, OkHttp thinks 1.2 is not supported at all.

    Sorry for this long bug report: I think the fix is as simple as changing getEnabledProtocols() above to getSupportedProtocols() but wanted to submit this bug for discussion before making a PR with such a change, in case there is some affirmative reason why it's the other way now.

    * Originally I understood the PCI compliance deadline to be June 2016; however, it seems like it has since been changed to be June 2018. Regardless, OkHttp should support this change for users that want it.

    android 
    opened by mlc 63
  • WARNING: A connection to https://... was leaked. Did you forget to close a response body?

    WARNING: A connection to https://... was leaked. Did you forget to close a response body?

    Version: com.squareup.okhttp3:okhttp:3.0.1

    Log message:

    <timestamp> okhttp3.ConnectionPool pruneAndGetAllocationCount
    WARNING: A connection to https://... was leaked. Did you forget to close a response body?
    

    Code:

    private String get(final String url) {
        String res = null;
        try {
            final Request req = new Request.Builder().url(url).get().build();
            final Response resp = ok.newCall(req).execute();
            final int code = resp.code();
            if (code == 200) {
                final ResponseBody body = resp.body();
                res = body.string();
                body.close(); // even this doesn't work!
            }
        }
        catch (final Throwable th) {
            System.out.println(th.getMessage());
        }
        return res;
    }
    
    opened by bxqgit 62
  • ETag and If-None-Match

    ETag and If-None-Match

    I have troubles with the ETag-based caching. I am using OkHttp 1.5.4 and Retrofit 1.5.1 with HttpResponseCache set. There are logs below for better explanation.

    The request with the Session header set to a token A. OkHttp hits the network, which is great.

    ---> HTTP GET https://localhost/shares
    Session: TOKEN_A
    Accept: application/json
    User-Agent: Application/1.0.0 (Android 4.4.2; Nexus 4) Size/4.7 Resolution/1280x768
    ---> END HTTP (0-byte body)
    <--- HTTP 200 https://localhost/shares (402ms)
    : HTTP/1.1 200 OK
    Content-Length: 136
    Content-Type: application/json
    Date: Sat, 17 May 2014 11:07:20 GMT
    Etag: "677210f4c22a13203551e2b92a20684528a23c87"
    Last-Modified: Sat, 17 May 2014 04:07:20 GMT
    OkHttp-Received-Millis: 1400324839589
    OkHttp-Response-Source: NETWORK 200
    OkHttp-Sent-Millis: 1400324839194
    <--- END HTTP (136-byte body)
    

    The second request with the Session header set to a token A. OkHttp hits the cache, which is great as well.

    ---> HTTP GET https://localhost/shares
    Session: TOKEN_A
    Accept: application/json
    User-Agent: Application/1.0.0 (Android 4.4.2; Nexus 4) Size/4.7 Resolution/1280x768
    ---> END HTTP (0-byte body)
    GC_FOR_ALLOC freed 415K, 5% free 9588K/10036K, paused 19ms, total 19ms
    <--- HTTP 200 https://localhost/shares (46ms)
    : HTTP/1.1 200 OK
    Content-Length: 136
    Content-Type: application/json
    Date: Sat, 17 May 2014 11:07:20 GMT
    Etag: "677210f4c22a13203551e2b92a20684528a23c87"
    Last-Modified: Sat, 17 May 2014 04:07:20 GMT
    OkHttp-Received-Millis: 1400324839589
    OkHttp-Response-Source: CACHE 200
    OkHttp-Sent-Millis: 1400324839194
    <--- END HTTP (136-byte body)
    

    The third request with the Session header set to token B. OkHttp hits the cache again, which is not so great, because in this case the server returns a different response with a different ETag actually.

    ---> HTTP GET https://localhost/shares
    Session: TOKEN_B
    Accept: application/json
    User-Agent: Application/1.0.0 (Android 4.4.2; Nexus 4) Size/4.7 Resolution/1280x768
    ---> END HTTP (0-byte body)
    <--- HTTP 200 https://localhost/shares (11ms)
    : HTTP/1.1 200 OK
    Content-Length: 136
    Content-Type: application/json
    Date: Sat, 17 May 2014 11:07:20 GMT
    Etag: "677210f4c22a13203551e2b92a20684528a23c87"
    Last-Modified: Sat, 17 May 2014 04:07:20 GMT
    OkHttp-Received-Millis: 1400324839589
    OkHttp-Response-Source: CACHE 200
    OkHttp-Sent-Millis: 1400324839194
    <--- END HTTP (136-byte body)
    

    Personally I expect to see the If-None-Match at the second and the third requests. Is the issue related to the lack of Cache-Control header at servers’s responses? Maybe I just don’t understand the caching strategy properly.

    opened by arturdryomov 50
  • HTTP/2 uses non-daemon threads

    HTTP/2 uses non-daemon threads

    The following one-line program does not close properly on Java 9:

    public static void main(String[] args) throws IOException {
        System.out.println(new OkHttpClient.Builder().build().newCall(new Request.Builder().url("https://google.de").build()).execute());
    }
    

    It hangs for a very significant amount of time after the request is already finished before it allows the program to quit.

    This a little modified version works flawlessly and allows the program to quit immediately after the request is finished.

    public static void main(String[] args) throws IOException {
        System.out.println(new OkHttpClient.Builder().protocols(Collections.singletonList(Protocol.HTTP_1_1)).build().newCall(new Request.Builder().url("https://google.de").build()).execute());
    }
    

    Running on Java 8 also fixes the problem, as there HTTP 1.1 is used, not HTTP 2.0.

    The problem is a hanging non-deamon thread called OkHttp google.de. Here you have the stacktrace of the thread when the program should quit:

    "OkHttp google.de@1876" prio=5 tid=0x11 nid=NA runnable
      java.lang.Thread.State: RUNNABLE
    	  at java.net.SocketInputStream.socketRead0(SocketInputStream.java:-1)
    	  at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
    	  at java.net.SocketInputStream.read(SocketInputStream.java:171)
    	  at java.net.SocketInputStream.read(SocketInputStream.java:141)
    	  at sun.security.ssl.SSLSocketInputRecord.read(SSLSocketInputRecord.java:425)
    	  at sun.security.ssl.SSLSocketInputRecord.bytesInCompletePacket(SSLSocketInputRecord.java:65)
    	  at sun.security.ssl.SSLSocketImpl.bytesInCompletePacket(SSLSocketImpl.java:918)
    	  - locked <0x792> (a java.lang.Object)
    	  at sun.security.ssl.AppInputStream.read(AppInputStream.java:144)
    	  - locked <0x793> (a sun.security.ssl.AppInputStream)
    	  at okio.Okio$2.read(Okio.java:140)
    	  at okio.AsyncTimeout$2.read(AsyncTimeout.java:237)
    	  at okio.RealBufferedSource.request(RealBufferedSource.java:68)
    	  at okio.RealBufferedSource.require(RealBufferedSource.java:61)
    	  at okhttp3.internal.http2.Http2Reader.nextFrame(Http2Reader.java:95)
    	  at okhttp3.internal.http2.Http2Connection$ReaderRunnable.execute(Http2Connection.java:608)
    	  at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
    	  at java.lang.Thread.run(Thread.java:844)
    

    I find it quite strange that this thread is hanging on a socketRead operation, while the request is already finished successfully.

    enhancement 
    opened by Vampire 49
  • ProtocolException: unexpected end of stream while downloading a file

    ProtocolException: unexpected end of stream while downloading a file

    Using a library which uses okhttp to download files, I am usually getting an unexpected end of stream error while downloading large files (thrown at the end of the download). I am using the following code and URL to reproduce the error:

    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url("http://speedtest-sfo1.digitalocean.com/100mb.test").build();
    client.newCall(request).enqueue(new Callback() {
    	public void onFailure(Call call, IOException e) {
    		e.printStackTrace();
    	}
    
    	public void onResponse(Call call, Response response) throws IOException {
    		if (!response.isSuccessful()) {
    			throw new IOException("Failed to download file: " + response);
    		}
    
    		FileOutputStream fos = new FileOutputStream(downloadDirectory + File.separator + "100mb.test");
    		fos.write(response.body().bytes());
    		fos.close();
    	}
    });
    

    URL: http://speedtest-sfo1.digitalocean.com/100mb.test (This is not the only URL the error is thrown on)

    The code has been tested on API 22, 25, 26, 27. The error is not thrown always, I tested it 10 times and got the error 6 times, 4 times the file got successfully downloaded and saved..

    I have read about the error and I know that it gets thrown when the servers sends incorrect Content-Length, not this time though. The file is exactly 100MB and the server supplies its correct length. I am not sending any extra request headers, the response headers are:

    Server => nginx/1.13.3
    Date => Sat, 09 Dec 2017 17:19:31 GMT
    Content-Type => text/plain
    Content-Length => 104857600
    Last-Modified => Mon, 27 Nov 2017 09:11:00 GMT
    Connection => close
    ETag => "5a1bd6a4-6400000"
    Access-Control-Allow-Origin => *
    Access-Control-Allow-Headers => Origin,X-RequestedWith,Content-Type,Range
    Access-Control-Allow-Methods => GET, OPTIONS
    Accept-Ranges => bytes
    Cache-Control => max-age=0, no-cache, no-store, mustrevalidate, no-transform
    
    

    The complete error:

    Callback failure for call to http://speedtest-sfo1.digitalocean.com/...
    java.net.ProtocolException: unexpected end of stream
        at okhttp3.internal.http1.Http1Codec$FixedLengthSource.read(Http1Codec.java:406)
        at okio.Buffer.writeAll(Buffer.java:1005)
        at okio.RealBufferedSource.readByteArray(RealBufferedSource.java:107)
        at okhttp3.ResponseBody.bytes(ResponseBody.java:136)
        at dm.com.downloadmanager.MainActivity$3.onResponse(MainActivity.java:273)
        at okhttp3.RealCall$AsyncCall.execute(RealCall.java:153)
        at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
        at java.lang.Thread.run(Thread.java:764)
    
    needs info 
    opened by ali-idrizi 48
  • IOException in DiskLruCache in 1.5.0.

    IOException in DiskLruCache in 1.5.0.

    Upgraded to v1.5.0 and I'm seeing a lot of these exceptions thrown.

    java.lang.RuntimeException: java.io.IOException: failed to delete /data/data/app.philm.in/cache/picasso-cache/452f1b31c49eebbd77673818036d6560.0
           at com.squareup.okhttp.internal.DiskLruCache$1.run(DiskLruCache.java:175)
           at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
           at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
           at java.lang.Thread.run(Thread.java:841)
    Caused by: java.io.IOException: failed to delete /data/data/app.philm.in/cache/picasso-cache/452f1b31c49eebbd77673818036d6560.0
           at com.squareup.okhttp.internal.DiskLruCache.remove(DiskLruCache.java:584)
           at com.squareup.okhttp.internal.DiskLruCache.trimToSize(DiskLruCache.java:639)
           at com.squareup.okhttp.internal.DiskLruCache.access$100(DiskLruCache.java:86)
           at com.squareup.okhttp.internal.DiskLruCache$1.run(DiskLruCache.java:169)
           at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
           at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
           at java.lang.Thread.run(Thread.java:841)
    
    opened by chrisbanes 48
  • Getting frequent D/OkHttp: <-- HTTP FAILED: java.net.SocketTimeoutException: failed to connect to <domain-name>/<ip> (port 8443) from /<ip-source> (port 50810) after 60000ms: isConnected failed: ETIMEDOUT (Connection timed out)

    Getting frequent D/OkHttp: <-- HTTP FAILED: java.net.SocketTimeoutException: failed to connect to / (port 8443) from / (port 50810) after 60000ms: isConnected failed: ETIMEDOUT (Connection timed out)

    I am getting frequent(one in 10 times average) D/OkHttp: <-- HTTP FAILED: java.net.SocketTimeoutException from my servers and I have set all timeouts(read, write, connect) to 60seconds but I get this exception in 8-10 seconds and there are no hits on my server for these requests.

    Some of the previously closed issues(https://github.com/square/okhttp/issues/6486) discuss IPv4 vs IPv6 issues at the client and/or server-side but my server supports only IPv4 and I made the client(android device) use IPv4 only still I am receiving this.

    Can someone please help here,

    Depos used - implementation 'com.squareup.retrofit2:retrofit:2.7.1' implementation "com.squareup.retrofit2:converter-moshi:2.6.2" implementation "com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2" implementation 'com.squareup.okhttp3:logging-interceptor:4.4.0' implementation 'com.squareup.retrofit2:converter-gson:2.7.1' implementation 'com.squareup.retrofit2:adapter-rxjava2:2.7.1' implementation 'com.squareup.retrofit2:converter-scalars:2.4.0'

    bug 
    opened by ganeshpadhayay 0
  • [Discussion] Add more connection failure tracking and tests.

    [Discussion] Add more connection failure tracking and tests.

    Unlikely to be correct, but if the ConnectPlan is the right place, then a few more questions.

    • Are there more places for routeDatabase.failed?
    • Where should routeDatabase.connected be called?
    • Which exceptions indicate serious problems?

    RealConnection.trackFailure doesn't look right for HTTP/2.

    opened by yschimke 1
  • routeDatabase.failed is not called when we fail to establish a connection

    routeDatabase.failed is not called when we fail to establish a connection

    When we have two ways of connecting to a destination, say IPv4 and IPv6. If the IPv4 connection then fails (say EOF due to server dying), it gets marked in the routeDatabase as failed. If the IPv6 connection then fails to connect (say the server doesn't support IPv6), it does not get marked in the routeDatabase as failed. This means that ALL future connection attempts will be over IPv6. Which will all fail. Even though the IPv4 connection has come back up and is now stable.

    What we should do: also mark routes where we fail to establish a connection as failed. Then the IPv6 (in our example) route would also be marked as failed, and given that all routes have failed, they will all be tried again. Including the IPv4 connection which would then work when the server has recovered.

    bug 
    opened by moshegood 2
  • OkHttp 4.10.0: Explicit termination method 'close' not called

    OkHttp 4.10.0: Explicit termination method 'close' not called

    I am using OkHttp 4.10.0 and I've just gotten this strict mode warning:

    StrictMode  D  StrictMode policy violation: android.os.strictmode.LeakedClosableViolation: A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resour
                  ce leaks.
               D      at android.os.StrictMode$AndroidCloseGuardReporter.report(StrictMode.java:1986)
               D      at dalvik.system.CloseGuard.warnIfOpen(CloseGuard.java:336)
               D      at java.io.FileOutputStream.finalize(FileOutputStream.java:495)
               D      at java.lang.Daemons$FinalizerDaemon.doFinalize(Daemons.java:319)
               D      at java.lang.Daemons$FinalizerDaemon.runInternal(Daemons.java:306)
               D      at java.lang.Daemons$Daemon.run(Daemons.java:140)
               D      at java.lang.Thread.run(Thread.java:1012)
               D  Caused by: java.lang.Throwable: Explicit termination method 'close' not called
               D      at dalvik.system.CloseGuard.openWithCallSite(CloseGuard.java:288)
               D      at dalvik.system.CloseGuard.open(CloseGuard.java:257)
               D      at java.io.FileOutputStream.<init>(FileOutputStream.java:253)
               D      at okio.Okio__JvmOkioKt.appendingSink(JvmOkio.kt:178)
               D      at okio.Okio.appendingSink(Unknown Source:1)
               D      at okhttp3.internal.io.FileSystem$Companion$SystemFileSystem.appendingSink(FileSystem.kt:66)
               D      at okhttp3.internal.cache.DiskLruCache.newJournalWriter(DiskLruCache.kt:302)
               D      at okhttp3.internal.cache.DiskLruCache.readJournal(DiskLruCache.kt:295)
               D      at okhttp3.internal.cache.DiskLruCache.initialize(DiskLruCache.kt:236)
               D      at okhttp3.internal.cache.DiskLruCache.get(DiskLruCache.kt:426)
               D      at okhttp3.Cache.get$okhttp(Cache.kt:172)
               D      at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.kt:47)
               D      at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
               D      at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.kt:83)
               D      at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
               D      at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.kt:76)
               D      at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
               D      at okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp(RealCall.kt:201)
               D      at okhttp3.internal.connection.RealCall.execute(RealCall.kt:154)
               D      at com.vanniktech.feature.rssreader.backend.DefaultRssFetcher$fetch$6$1.invokeSuspend(DefaultRssFetcher.kt:151)
               D      at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
               D      at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
               D      at kotlinx.coroutines.internal.LimitedDispatcher.run(LimitedDispatcher.kt:42)
               D      at kotlinx.coroutines.scheduling.TaskImpl.run(Tasks.kt:95)
               D      at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:570)
               D      at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
               D      at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:677)
               D      at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:664)
    

    I can see that newJournalWriter() is called here: https://github.com/square/okhttp/blob/e46a200fceaa5fbd9c9278eebe9c978399bd329c/okhttp/src/main/kotlin/okhttp3/internal/cache/DiskLruCache.kt#L295 and it's closed here: https://github.com/square/okhttp/blob/e46a200fceaa5fbd9c9278eebe9c978399bd329c/okhttp/src/main/kotlin/okhttp3/internal/cache/DiskLruCache.kt#L679

    I'm not familiar with the code but can it be that when newJournalWriter() there is already a journalWriter set which would need to be closed?!

    My calling site (DefaultRssFetcher:151) looks like this:

    withContext(Dispatchers.IO) { 
      okHttpClient.newCall(makeRequest(url).execute() }.use { response ->
        ...
      }
    }
    

    So I do close the response that I get from OkHttp.

    bug needs info 
    opened by vanniktech 8
Standalone Play WS, an async HTTP client with fluent API

Play WS Standalone Play WS is a powerful HTTP Client library, originally developed by the Play team for use with Play Framework. It uses AsyncHttpClie

Play Framework 213 Dec 15, 2022
Realtime Client Server Framework for the JVM, supporting WebSockets with Cross-Browser Fallbacks

Welcome to Atmosphere: The Event Driven Framework supporting WebSocket and HTTP The Atmosphere Framework contains client and server side components fo

Atmosphere Framework 3.6k Jan 3, 2023
This is an open source android based Music Player application developed in Android Studio

Pulse Music An offline music player android app, with modern UI and powerful features If you liked this repo, fork it and leave a STAR. Your support m

Sharath 7 Apr 11, 2022
A Java event based WebSocket and HTTP server

Webbit - A Java event based WebSocket and HTTP server Getting it Prebuilt JARs are available from the central Maven repository or the Sonatype Maven r

null 808 Dec 23, 2022
The Java gRPC implementation. HTTP/2 based RPC

gRPC-Java - An RPC library and framework gRPC-Java works with JDK 7. gRPC-Java clients are supported on Android API levels 16 and up (Jelly Bean and l

grpc 10.2k Jan 1, 2023
Magician is an asynchronous non-blocking network protocol analysis package, supports TCP, UDP protocol, built-in Http, WebSocket decoder

An asynchronous non-blocking network protocol analysis package Project Description Magician is an asynchronous non-blocking network protocol analysis

贝克街的天才 103 Nov 30, 2022
HTTP Server Model made in java

SimplyJServer HTTP Server Model made in java Features Fast : SimplyJServer is 40%-60% faster than Apache, due to it's simplicity. Simple to implement

Praudyogikee for Advanced Technology 2 Sep 25, 2021
Telegram API Client and Telegram BOT API Library and Framework in Pure java.

Javagram Telegram API Client and Telegram Bot API library and framework in pure Java. Hello Telegram You can use Javagram for both Telegram API Client

Java For Everything 3 Oct 17, 2021
Android application allowing to sniff and inject Zigbee, Mosart and Enhanced ShockBurst packets on a Samsung Galaxy S20

RadioSploit 1.0 This Android application allows to sniff and inject Zigbee, Mosart and Enhanced ShockBurst packets from a Samsung Galaxy S20 smartphon

Romain Cayre 52 Nov 1, 2022
Full-featured Socket.IO Client Library for Java, which is compatible with Socket.IO v1.0 and later.

Socket.IO-client Java This is the Socket.IO Client Library for Java, which is simply ported from the JavaScript client. See also: Android chat demo en

Socket.IO 5k Jan 4, 2023
BAIN Social is a Fully Decentralized Server/client system that utilizes Concepts pioneered by I2P, ToR, and PGP to create a system which bypasses singular hosts for data while keeping that data secure.

SYNOPSIS ---------------------------------------------------------------------------------------------------- Welcome to B.A.I.N - Barren's A.I. Natio

Barren A.I. Wolfsbane 14 Jan 11, 2022
IoT Platform, Device management, data collection, processing and visualization, multi protocol, rule engine, netty mqtt client

GIoT GIoT: GIoT是一个开源的IoT平台,支持设备管理、物模型,产品、设备管理、规则引擎、多种存储、多sink、多协议(http、mqtt、tcp,自定义协议)、多租户管理等等,提供插件化开发 Documentation Quick Start Module -> giot-starte

gerry 34 Sep 13, 2022
A barebones WebSocket client and server implementation written in 100% Java.

Java WebSockets This repository contains a barebones WebSocket server and client implementation written in 100% Java. The underlying classes are imple

Nathan Rajlich 9.5k Dec 30, 2022
A small java project consisting of Client and Server, that communicate via TCP/UDP protocols.

Ninja Battle A small java project consisting of Client and Server, that communicate via TCP/UDP protocols. Client The client is equipped with a menu i

Steliyan Dobrev 2 Jan 14, 2022
TCP/UDP client/server library for Java, based on Kryo

KryoNet can be downloaded on the releases page. Please use the KryoNet discussion group for support. Overview KryoNet is a Java library that provides

Esoteric Software 1.7k Jan 2, 2023
Proteus Java Client

Netifi Proteus Java This project has been moved to https://github.com/netifi/netifi-java Build from Source Run the following Gradle command to build t

netifi-proteus 42 Nov 20, 2020
Socket.IO Client Implementation in Java

Socket.IO-Client for Java socket.io-java-client is an easy to use implementation of socket.io for Java. It uses Weberknecht as transport backend, but

Enno Boland 946 Dec 21, 2022
Book Finder application is a client-server application (gRPC) for educational purposes.

Book-Finder Book Finder application is a client-server application (gRPC) for educational purposes. Instalation These projects (Client/Server) are Mav

Mihai-Lucian Rîtan 21 Oct 27, 2022