- Okhttp3 android post request
- 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
- Okhttp3 android post request
- Recipes¶
- Synchronous Get (.kt, .java)¶
- Asynchronous Get (.kt, .java)¶
- Accessing Headers (.kt, .java)¶
- Posting a String (.kt, .java)¶
- Post Streaming (.kt, .java)¶
- Posting a File (.kt, .java)¶
- Posting form parameters (.kt, .java)¶
- Posting a multipart request (.kt, .java)¶
- Parse a JSON Response With Moshi (.kt, .java)¶
- Response Caching (.kt, .java)¶
- Canceling a Call (.kt, .java)¶
- Timeouts (.kt, .java)¶
- Per-call Configuration (.kt, .java)¶
- Handling authentication (.kt, .java)¶
Okhttp3 android post request
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.
Источник
Okhttp3 android post request
Most apps need network connections to external services to access and exchange data. OKHttp is an Android HTTP client library from Square that reduces the steps needed.
OKHttp removes the need for network testing, recovering from common connection problems, and on a connection failure, it can retry the request with a different route.
OKHttp is built on top of the Okio library, which tries to be more efficient about reading and writing data than the standard Java I/O libraries by creating a shared memory pool. It also is the underlying library for Retrofit library that provides type safety for consuming REST-based APIs.
Also OKHttp supports both synchronous blocking calls and async calls with callbacks.
Let’s add dependencies. Open build.gradle and add the following dependency, or check the OKHttp site for the latest updates.
Makes sure to enable the use of the Internet permission in your AndroidManifest.xml file
Creating request objects for make network calls
To use OkHttp you need to create a Request object.
You can also add parameters
If there are any authenticated query parameters, headers can be added to the request too
Sending and receiving network calls
To make a synchronous network call, use the Client to create a Call object and use the execute method.
To make asynchronous calls, also create a Call object but use the enqueue method, and passing an anonymous callback object that implements both onFailure() and onResponse() .
OkHttp creates a new worker thread to dispatch the network request and uses the same thread to handle the response. If you need to update any views, you will need to use runOnUiThread() or post the result back on the main thread.
Assuming the request is not cancelled and there are no connectivity issues, the onResponse() method will be fired. It passes a Response object that can be used to check the status code, the response body , and any headers that were returned. Calling isSuccessful() for instance if the code returned a status code of 2XX (i.e. 200, 201, etc.)
The header responses are also provided as a list:
The headers can also be access directly using response.header() :
We can also decode the JSON-based data by using Gson.
Caching network responses
We can setup network caching by passing in a cache when building the OkHttpClient :
We can control whether to retrieve a cached response by setting the cacheControl property on the request. For instance, if we wish to only retrieve the request if data is cached, we could construct the Request object as follows:
We can also force a network response by using noCache() for the request:
We can also specify a maximum staleness age for the cached response:
To retrieve the cached response, we can simply call cacheResponse() on the Response object:
POST request to server
We can send POST request to server using following approach
Источник
Recipes¶
We’ve written some recipes that demonstrate how to solve common problems with OkHttp. Read through them to learn about how everything works together. Cut-and-paste these examples freely; that’s what they’re for.
Synchronous Get (.kt, .java)¶
Download a file, print its headers, and print its response body as a string.
The string() method on response body is convenient and efficient for small documents. But if the response body is large (greater than 1 MiB), avoid string() because it will load the entire document into memory. In that case, prefer to process the body as a stream.
Asynchronous Get (.kt, .java)¶
Download a file on a worker thread, and get called back when the response is readable. The callback is made after the response headers are ready. Reading the response body may still block. OkHttp doesn’t currently offer asynchronous APIs to receive a response body in parts.
Accessing Headers (.kt, .java)¶
Typically HTTP headers work like a Map : each field has one value or none. But some headers permit multiple values, like Guava’s Multimap. For example, it’s legal and common for an HTTP response to supply multiple Vary headers. OkHttp’s APIs attempt to make both cases comfortable.
When writing request headers, use header(name, value) to set the only occurrence of name to value . If there are existing values, they will be removed before the new value is added. Use addHeader(name, value) to add a header without removing the headers already present.
When reading response a header, use header(name) to return the last occurrence of the named value. Usually this is also the only occurrence! If no value is present, header(name) will return null. To read all of a field’s values as a list, use headers(name) .
To visit all headers, use the Headers class which supports access by index.
Posting a String (.kt, .java)¶
Use an HTTP POST to send a request body to a service. This example posts a markdown document to a web service that renders markdown as HTML. Because the entire request body is in memory simultaneously, avoid posting large (greater than 1 MiB) documents using this API.
Post Streaming (.kt, .java)¶
Here we POST a request body as a stream. The content of this request body is being generated as it’s being written. This example streams directly into the Okio buffered sink. Your programs may prefer an OutputStream , which you can get from BufferedSink.outputStream() .
Posting a File (.kt, .java)¶
It’s easy to use a file as a request body.
Posting form parameters (.kt, .java)¶
Use FormBody.Builder to build a request body that works like an HTML tag. Names and values will be encoded using an HTML-compatible form URL encoding.
Posting a multipart request (.kt, .java)¶
MultipartBody.Builder can build sophisticated request bodies compatible with HTML file upload forms. Each part of a multipart request body is itself a request body, and can define its own headers. If present, these headers should describe the part body, such as its Content-Disposition . The Content-Length and Content-Type headers are added automatically if they’re available.
Parse a JSON Response With Moshi (.kt, .java)¶
Moshi is a handy API for converting between JSON and Java objects. Here we’re using it to decode a JSON response from a GitHub API.
Note that ResponseBody.charStream() uses the Content-Type response header to select which charset to use when decoding the response body. It defaults to UTF-8 if no charset is specified.
Response Caching (.kt, .java)¶
To cache responses, you’ll need a cache directory that you can read and write to, and a limit on the cache’s size. The cache directory should be private, and untrusted applications should not be able to read its contents!
It is an error to have multiple caches accessing the same cache directory simultaneously. Most applications should call new OkHttpClient() exactly once, configure it with their cache, and use that same instance everywhere. Otherwise the two cache instances will stomp on each other, corrupt the response cache, and possibly crash your program.
Response caching uses HTTP headers for all configuration. You can add request headers like Cache-Control: max-stale=3600 and OkHttp’s cache will honor them. Your webserver configures how long responses are cached with its own response headers, like Cache-Control: max-age=9600 . There are cache headers to force a cached response, force a network response, or force the network response to be validated with a conditional GET.
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.
Canceling a Call (.kt, .java)¶
Use Call.cancel() to stop an ongoing call immediately. If a thread is currently writing a request or reading a response, it will receive an IOException . Use this to conserve the network when a call is no longer necessary; for example when your user navigates away from an application. Both synchronous and asynchronous calls can be canceled.
Timeouts (.kt, .java)¶
Use timeouts to fail a call when its peer is unreachable. Network partitions can be due to client connectivity problems, server availability problems, or anything between. OkHttp supports connect, write, read, and full call timeouts.
Per-call Configuration (.kt, .java)¶
All the HTTP client configuration lives in OkHttpClient including proxy settings, timeouts, and caches. When you need to change the configuration of a single call, call OkHttpClient.newBuilder() . This returns a builder that shares the same connection pool, dispatcher, and configuration with the original client. In the example below, we make one request with a 500 ms timeout and another with a 3000 ms timeout.
Handling authentication (.kt, .java)¶
OkHttp can automatically retry unauthenticated requests. When a response is 401 Not Authorized , an Authenticator is asked to supply credentials. Implementations should build a new request that includes the missing credentials. If no credentials are available, return null to skip the retry.
Use Response.challenges() to get the schemes and realms of any authentication challenges. When fulfilling a Basic challenge, use Credentials.basic(username, password) to encode the request header.
To avoid making many retries when authentication isn’t working, you can return null to give up. For example, you may want to skip the retry when these exact credentials have already been attempted:
You may also skip the retry when you’ve hit an application-defined attempt limit:
This above code relies on this responseCount() method:
Источник