Apa maksud logging interceptor pada android studio

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.3")

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.3")) // 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.3")

GraalVM Native Image¶

Building your native images with Graal https://www.graalvm.org/ should work automatically. This is not currently in a final released version, so 5.0.0-alpha.2 should be used. 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.


Page 2

//okhttp/okhttp3

Types¶

Name Summary
Address [jvm]
class Address(uriHost: String, uriPort: Int, val dns: Dns, val socketFactory: SocketFactory, val sslSocketFactory: SSLSocketFactory?, val hostnameVerifier: HostnameVerifier?, val certificatePinner: CertificatePinner?, val proxyAuthenticator: Authenticator, val proxy: Proxy?, protocols: List<Protocol>, connectionSpecs: List<ConnectionSpec>, val proxySelector: ProxySelector)
A specification for a connection to an origin server. For simple connections, this is the server’s hostname and port. If an explicit proxy is requested (or no proxy is explicitly requested), this also includes that proxy information. For secure connections the address also includes the SSL socket factory, hostname verifier, and certificate pinner.
AsyncDns [jvm]
interface AsyncDns
An async domain name service that resolves IP addresses for host names.
Authenticator [jvm]
fun interface Authenticator
Performs either preemptive authentication before connecting to a proxy server, or reactive authentication after receiving a challenge from either an origin web server or proxy server.
Cache [jvm]
class Cache(directory: Path, maxSize: Long, fileSystem: FileSystem) : Closeable, Flushable
Caches HTTP and HTTPS responses to the filesystem so they may be reused, saving time and bandwidth.
CacheControl [common]
expect class CacheControlA Cache-Control header with cache directives from a server or client. These directives set policy on what responses can be stored, and which requests can be satisfied by those stored responses.[jvm, nonJvm][jvm, nonJvm]

actual class CacheControl

Call [common]
expect interface CallA call is a request that has been prepared for execution. A call can be canceled. As this object represents a single request/response pair (stream), it cannot be executed twice.[jvm, nonJvm][jvm]

actual interface Call : Cloneable

[nonJvm]

actual interface Call

Callback [common]
interface Callback
CertificatePinner [jvm]
class CertificatePinner
Constrains which certificates are trusted. Pinning certificates defends against attacks on certificate authorities. It also prevents connections through man-in-the-middle certificate authorities either known or unknown to the application’s user. This class currently pins a certificate’s Subject Public Key Info as described on Adam Langley’s Weblog. Pins are either base64 SHA-256 hashes as in HTTP Public Key Pinning (HPKP) or SHA-1 base64 hashes as in Chromium’s static certificates.
Challenge [common]
expect class Challenge(scheme: String, authParams: Map<String?, String>)
An RFC 7235 challenge.[jvm, nonJvm][jvm, nonJvm]

actual class Challenge(val scheme: String, authParams: Map<String?, String>)

CipherSuite [jvm]
class CipherSuite
TLS cipher suites.
Connection [jvm]
interface Connection
The sockets and streams of an HTTP, HTTPS, or HTTPS+HTTP/2 connection. May be used for multiple HTTP request/response exchanges. Connections may be direct to the origin server or via a proxy.
ConnectionPool [jvm]
class ConnectionPool
Manages reuse of HTTP and HTTP/2 connections for reduced network latency. HTTP requests that share the same Address may share a Connection. This class implements the policy of which connections to keep open for future use.
ConnectionSpec [jvm]
class ConnectionSpec
Specifies configuration for the socket connection that HTTP traffic travels through. For https: URLs, this includes the TLS version and cipher suites to use when negotiating a secure connection.
Cookie [jvm]
class Cookie
An RFC 6265 Cookie.
CookieJar [jvm]
interface CookieJar
Provides policy and persistence for HTTP cookies.
Credentials [jvm]
object Credentials
Factory for HTTP authorization credentials.
Dispatcher [jvm]
class Dispatcher
Policy on when async requests are executed.
Dns [jvm]
fun interface Dns
A domain name service that resolves IP addresses for host names. Most applications will use the system DNS service, which is the default. Some applications may provide their own implementation to use a different DNS server, to prefer IPv6 addresses, to prefer IPv4 addresses, or to force a specific known IP address.
EventListener [jvm]
abstract class EventListener
Listener for metrics events. Extend this class to monitor the quantity, size, and duration of your application’s HTTP calls.
FormBody [jvm]
class FormBody : RequestBody
Handshake [jvm]
class Handshake
A record of a TLS handshake. For HTTPS clients, the client is local and the remote server is its peer.
Headers [common]
expect class Headers : Iterable<Pair<String, String>> The header fields of a single HTTP message. Values are uninterpreted strings; use Request and Response for interpreted headers. This class maintains the order of the header fields within the HTTP message.[jvm, nonJvm][jvm]

actual class Headers : Iterable<Pair<String, String>>

[nonJvm]

actual class Headers : Iterable<<ERROR CLASS><String, String>>

HttpUrl [jvm]
class HttpUrl
A uniform resource locator (URL) with a scheme of either http or https. Use this class to compose and decompose Internet addresses. For example, this code will compose and print a URL for Google search:
Interceptor [jvm]
fun interface Interceptor
Observes, modifies, and potentially short-circuits requests going out and the corresponding responses coming back in. Typically interceptors add, remove, or transform headers on the request or response.
MediaType [common]
expect class MediaType
An RFC 2045 Media Type, appropriate to describe the content type of an HTTP request or response body.[jvm, nonJvm][jvm, nonJvm]

actual class MediaType

MultipartBody [jvm]
class MultipartBody : RequestBody
An RFC 2387-compliant request body.
MultipartReader [jvm]
class MultipartReaderconstructor(source: BufferedSource, val boundary: String) : Closeable
Reads a stream of RFC 2046 multipart body parts. Callers read parts one-at-a-time until nextPart returns null. After calling nextPart any preceding parts should not be read.
OkHttp [common]
object OkHttp
OkHttpClient [jvm]
open class OkHttpClient : Call.Factory, WebSocket.Factory
Factory for calls, which can be used to send HTTP requests and read their responses.
Protocol [common]
enum Protocol : Enum<Protocol>
Protocols that OkHttp implements for ALPN selection.
ProtocolException [common, nonJvm, jvm][common]

expect class ProtocolException(message: String)

[nonJvm]

actual class ProtocolException(message: String) : IOException

[jvm]

actual typealias ProtocolException = ProtocolException

Request [common]
expect class Request
An HTTP request. Instances of this class are immutable if their body is null or itself immutable.[jvm, nonJvm][jvm, nonJvm]

actual class Request

RequestBody [common, jvm, nonJvm][common]

expect abstract class RequestBody

[jvm, nonJvm]

actual abstract class RequestBody

Response [common, nonJvm][common]

expect class Response

[nonJvm]

actual class Response : Closeable

An HTTP response. Instances of this class are not immutable: the response body is a one-shot value that may be consumed only once and then closed. All other properties are immutable.[jvm]

actual class Response : Closeable

ResponseBody [common]
expect abstract class ResponseBodyA one-shot stream from the origin server to the client application with the raw bytes of the response body. Each response body is supported by an active connection to the webserver. This imposes both obligations and limits on the client application.[jvm, nonJvm][jvm]

actual abstract class ResponseBody : Closeable

[nonJvm]

actual abstract class ResponseBody : Closeable

Route [jvm]
class Route(val address: Address, val proxy: Proxy, val socketAddress: InetSocketAddress)
The concrete route used by a connection to reach an abstract origin server. When creating a connection the client has many options:
TlsVersion [common]
expect enum TlsVersion : Enum<TlsVersion> Versions of TLS that can be offered when negotiating a secure socket.[jvm]

actual enum TlsVersion : Enum<TlsVersion>


Versions of TLS that can be offered when negotiating a secure socket. See javax.net.ssl.SSLSocket.setEnabledProtocols.[nonJvm]

actual enum TlsVersion : Enum<TlsVersion>

WebSocket [jvm]
interface WebSocket
A non-blocking interface to a web socket. Use the factory to create instances; usually this is OkHttpClient.
WebSocketListener [jvm]
abstract class WebSocketListener