- Руководство по OkHttp
- 1. Введение
- 2. Обзор OkHttp
- 3. Зависимость от Maven
- 4. Синхронный GET с OkHttp
- 5. Асинхронный GET с OkHttp
- 6. GET с параметрами запроса
- 7. Запрос POST
- 8. Загрузка файла
- 8.1. Загрузить файл
- 8.2. Получить прогресс загрузки файла
- 9. Установка собственного заголовка
- 9.1. Setting a Header on a Request
- 9.2. Setting a Default Header
- 10. Do Not Follow Redirects
- 11. Timeouts
- 12. Canceling a Call
- 13. Response Caching
- 14. Conclusion
- Okhttp примеры java android
- Android OkHttp Example
- OkHttp Supports Http/2
- Features of OkHttp.
- Add Library to Project
- Add Permission to Manifest
- Android OkHttp Examples
- Android OkHttp Get Example
- Android OkHttp Get Request With Query String Example
- Android OkHttp Post Example
- Android OkHttp POST JSON Example
- Android OkHttp Headers Example
- Android OkHttp Async Call
- Android OkHttp Multipart Example
- Android OkHttp Example Code
- Activity
- Layout
- About
- OkHttp¶
- Get a URL¶
- Post to a Server¶
- Requirements¶
- Releases¶
- MockWebServer¶
- GraalVM Native Image¶
Руководство по OkHttp
1. Введение
В этой статье мы покажем основы отправки различных типов HTTP-запросов, получения и интерпретации HTTP-ответов и того , как настроить клиента с помощью OkHttp.
Кроме того, мы рассмотрим более сложные варианты использования настройки клиента с использованием настраиваемых заголовков, тайм-аутов, кеширования ответов и т. Д.
2. Обзор OkHttp
OkHttp — это эффективный клиент HTTP и HTTP / 2 для приложений Android и Java.
Он поставляется с расширенными функциями, такими как пул соединений (если HTTP / 2 недоступен), прозрачное сжатие GZIP и кеширование ответов, чтобы полностью исключить сеть для повторных запросов.
Он также может восстанавливаться после распространенных проблем с подключением, а в случае сбоя подключения, если служба имеет несколько IP-адресов, она может повторить запрос на альтернативные адреса.
На высоком уровне клиент предназначен как для блокировки синхронных, так и для неблокируемых асинхронных вызовов.
OkHttp поддерживает Android 2.3 и выше. Для Java минимальное требование — 1,7.
После этого краткого обзора давайте рассмотрим несколько примеров использования.
3. Зависимость от Maven
Давайте сначала добавим библиотеку в качестве зависимости в pom.xml :
Чтобы увидеть последнюю зависимость этой библиотеки, посетите страницу в Maven Central.
4. Синхронный GET с OkHttp
Чтобы отправить синхронный запрос GET, нам нужно создать объект запроса на основе URL-адреса и выполнить вызов . После его выполнения мы возвращаем экземпляр Response :
5. Асинхронный GET с OkHttp
Теперь, чтобы сделать асинхронный GET, нам нужно поставить в очередь вызов . Обратный вызов позволяет прочитать ответ , когда он читается. Это происходит после того, как заголовки ответа готовы.
Чтение тела ответа все еще может блокироваться. OkHttp в настоящее время не предлагает никаких асинхронных API для получения тела ответа по частям:
6. GET с параметрами запроса
Наконец, чтобы добавить параметры запроса к нашему GET-запросу, мы можем воспользоваться HttpUrl.Builder .
После создания URL-адреса мы можем передать его нашему объекту Request :
7. Запрос POST
Давайте посмотрим на простой запрос POST, в котором мы создаем RequestBody для отправки параметров «имя пользователя» и «пароль» :
В нашей статье Краткое руководство по отправке запросов с OkHttp есть больше примеров запросов POST с OkHttp.
8. Загрузка файла
8.1. Загрузить файл
В этом примере мы увидим, как загрузить файл . Мы загрузим файл test.ext с помощью MultipartBody.Builder :
8.2. Получить прогресс загрузки файла
Наконец, давайте посмотрим, как узнать о ходе загрузки файла . Мы расширим RequestBody, чтобы видеть процесс загрузки.
Во-первых, вот метод загрузки:
Вот интерфейс ProgressListener, который позволяет нам наблюдать за процессом загрузки:
Вот ProgressRequestWrapper, расширенная версия RequestBody :
Наконец, вот CountingSink, который является расширенной версией Forwarding Sink :
Обратите внимание, что:
- При расширении ForwardingSink до «CountingSink» мы переопределяем метод write () для подсчета записанных (переданных) байтов.
- При расширении RequestBody до « ProgressRequestWrapper » мы переопределяем метод writeTo () для использования нашего «ForwardingSink»
9. Установка собственного заголовка
9.1. Setting a Header on a Request
To set any custom header on a Request we can use a simple addHeader call:
9.2. Setting a Default Header
In this example, we will see how to configure a default header on the Client itself, instead of setting it on each and every request.
For example, if we want to set a content type “application/json” for every request we need to set an interceptor for our client. Here is the method:
And here is the DefaultContentTypeInterceptor which is the extended version of Interceptor:
Note that the interceptor adds the header to the original request.
10. Do Not Follow Redirects
In this example, we’ll see how to configure the OkHttpClient to stop following redirects.
By default, if a GET request is answered with an HTTP 301 Moved Permanently the redirect is automatically followed. In some use cases, that may be perfectly fine, but there are certainly use cases where that’s not desired.
To achieve this behavior, when we build our client, we need to set followRedirects to false.
Note that the response will return an HTTP 301 status code:
If we turn on the redirect with a true parameter (or remove it completely), the client will follow the redirection and the test will fail as the return code will be an HTTP 200.
11. Timeouts
Use timeouts to fail a call when its peer is unreachable. Network failures can be due to client connectivity problems, server availability problems, or anything between. OkHttp supports connect, read, and write timeouts.
In this example, we built our client with a readTimeout of 1 seconds, while the URL is served with 2 seconds of delay:
Note as the test will fail as the client timeout is lower than the resource response time.
12. Canceling a Call
Use Call.cancel() to stop an ongoing call immediately. If a thread is currently writing a request or reading a response, an IOException will be thrown.
Use this to conserve the network when a call is no longer necessary; for example when your user navigates away from an application:
13. Response Caching
To create a Cache, we’ll need a cache directory that we can read and write to, and a limit on the cache’s size.
The client will use it to cache the response:
After launching the test, the response from the first call will not have been cached. A call to the method cacheResponse will return null, while a call to the method networkResponse will return the response from the network.
Also, the cache folder will be filled with the cache files.
The second call execution will produce the opposite effect, as the response will have already been cached. This means that a call to networkResponse will return null while a call to cacheResponse will return the response from the cache.
To prevent a response from using the cache, use CacheControl.FORCE_NETWORK. To prevent it from using the network, use CacheControl.FORCE_CACHE.
Be warned: if you use FORCE_CACHE and the response requires the network, OkHttp will return a 504 Unsatisfiable Request response.
14. Conclusion
In this article, we have seen several examples of how to use OkHttp as an HTTP & HTTP/2 client.
Как всегда, пример кода можно найти в проекте GitHub.
Источник
Okhttp примеры java android
Android OkHttp Example
May 27, 2017 by Srinivas
Android apps rely on rest services running on server for authentication & authorization, getting and posting data. Since the services on the web run on http protocol, in order to network with servers, android apps need http client. While there are several http client libraries and frameworks including volley which can be used in Android, OkHttp, an Http & Http/2 client, is widely used in android and java applications.
In this article, I am going to explain features of OkHttp and show how to use OkHttp in android to make http get, post, multipart, json and asynchronous request calls with examples.
OkHttp Supports Http/2
Below are some of the features of http/2
- Http/2 is a binary protocol which is more efficient compared to text protocol Http.
- Http/2 supports multiplexing meaning multiple requests and responses can be in flight at the same time on a connection.
- Http/2 supports header compression leading to reduced network round trips.
- Http/2 provides improved security.
Features of OkHttp.
OkHttp supports below features which make OkHttp an efficient http client with fast loading and reduced network bandwidth.
- OkHttp supports Http/2 protocol.
- Connection pooling can used for http protocol connections.
- GZIP compression shrinks network data size.
- Cache eliminates network round trip for repeating requests.
- OkHttp silently recovers from network problems.
- If your server is load balanced, OkHttp tries to connect other nodes when it fails to connect one of the nodes in load balancer.
- OkHttp supports both synchronous and asynchronous calls.
- You can use OkHttp on Android 2.3 and Java 7 versions onwards.
Add Library to Project
You can add OkHttp library to your project by adding below line to your module gradle property file.
Add Permission to Manifest
As below examples access rest services on server, internet permission is required. Add below permission to manifest xml file.
Android OkHttp Examples
In the below examples, the process of making reset service calls and updating UI with responses is executed in the background thread using AsyncTask. I provided below detailed explanation of each type of http request and complete android OkHttp example code.
Android OkHttp Get Example
Below code shows how to send http get request using OkHttp. To make an http get request call using OkHttp, you need to create Request object by using Request.Builder. Then call newCall method on OkHttpClient object passing the Request object. Finally, call execute() method on Call object to make http get request and receive response.
Above service call returns response in JSON format. Once you get JSON string from response by calling response.body().string(), you can use JSONOjbect or gson for parsing it. If you need more information on how to parse json in android, you can view my previous posts parsing JSON using JSONObject and parsing Json using gson library.
Android OkHttp Get Request With Query String Example
To make http get request call with query parameter using OkHttp, you need to use HttpUrl.Builder and add query parameter to it by calling addQueryParameter on HttpUrl.Builder as shown in below code.
Android OkHttp Post Example
To add post data to Request as key value pairs like data from html forms, you need to use FormBody.Builder, add post parameters to it, and create RequestBody as shown below.
Android OkHttp POST JSON Example
You can post json string to server using OkHttp. To do that, you need to create RequestBody object using create method on RequestBody passing json MediaType and json string as show below.
Android OkHttp Headers Example
You can add headers to request when request object is created or in intercepters by calling addHeader method on Request.Builder object.
Android OkHttp Async Call
In our examples, as UI needs to be updated with response after service call, entire process of making service calls and updating UI is done in the background using AsyncTask. But if you don’t need to use AsyncTask but only want to make http call asynchronously, you can do so by calling enqueue method on Call object passing Callback instead of execute method which makes http call synchronously.
Android OkHttp Multipart Example
To upload files or send multiple parts to http server, you need to send http multipart request. You can create multipart requests in OkHttp by building RequestBody using MultipartBody.Builder shown below. MultipartBody.Builder allows you to add data parts using addFormDataPart method.
Android OkHttp Example Code
Activity
Layout
About
Android app development tutorials and web app development tutorials with programming examples and code samples.
Источник
OkHttp¶
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.
Post to a Server¶
This program posts data to a service. Full source.
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:
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.
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.
MockWebServer¶
OkHttp includes a library for testing HTTP, HTTPS, and HTTP/2 clients.
The latest release is available on Maven Central.
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.
Источник