Okhttp android studio подключить

OkHttp: Android Tutorial

Most of internet content distribution it is still done through HTTP, which means that anyone building a mobile app will be obviously dealing with HTTP Libs. Since we are working to improve the performance of content distribution on mobile apps (find more about it here), there was no doubt that our Bolina SDK would have to be seamlessly integrated with, at least, the most popular HTTP Libs out there. That was how I decided to start exploring the HTTP Libs landscape (all tutorials and performance-related articles, here).

During this process, I figured out that, features-wise, OkHTTP is my favorite. OkHTTP is Square’s answer for HTTP needs, by being “an HTTP client that’s efficient by default”. It becomes efficient by automatically caching HTTP response, automatically compressing HTTP data and performing connection pooling. Besides this, OkHTTP also has robustness as a goal, by employing a few strategies to automatically recover in case of a connection fail. Moreover, it has been developed to support HTTP/2 from the beginning.

In this tutorial I will show you how to integrate OkHTTP into an Android project (literally a clean, straight-out-of-the-Android-Studio new project wizard). It will create 2 HTTP calls, a GET and a POST to a publicly available RESTful API, hosted by reqres.in, a service “that allows us to test our front-end against a real API”.

Integrating OkHTTP Library

First, add the permission to the application’s manifest to allow the application to access the Internet:

To integrate the OkHTTP library into a project, we must include the OkHTTP dependency to the project’s gradle:

OkHTTP library exposes both synchronous and asynchronous methods to perform HTTP calls. I really like asynchronous methods, given that it removes the pain of managing the worker thread ourselves.

To perform a GET call, just add the following code to your project:

I start by creating a new OkHTTPClient instance and by creating a new request. Finally, I just ask OkHTTP to perform the get request and to asynchronously notify when the response from the server is successful. That’s it, very simple!

To perform a POST call, just add the following code to your project:

I start by creating a new OkHTTPClient instance and by creating a JSON with data to post to the server.

Notice that in order to create JSON objects, include the GSON dependency to the project:

After creating the JSON data, I create the post request and set it to send JSON data. Finally, I just ask OkHTTP to perform the post request and to asynchronously notify when the response from the server is successful. Again, simple!

OkHTTP also allows HTTP calls to be run synchronously. To use those, instead of using the method enqueue, just use the method execute.

Full Project Code

The full code used is available on Github. Feel free to adapt it to your specific needs. I hope this tutorial helped you understanding how to integrate OKHttp into an Android project. If this wasn’t the right solution for you, you can also check the integration tutorial for HttpURLConnection, which is a more mature HTTP library. To help you decide, you can also check my performance comparison post, where I reveal which one is faster. Find out here!

Источник

Okhttp android studio подключить

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.

Источник

How to make client android application with Flask server

You will learn how to connect android studio with flask server.

We all know that mobile devices are not powerful compared to PCs, we can do a lot of things with our smart phones but with limited resources, most of us consider that like a weakness point.

So, from the previous paragraph, we can conclude that mobile devices are not the best choice for many things such as machine learning.When we say machine learning we must also mention deep learning, because this last one is included in it, and for the record, deep neural network needs a lot of samples to be trained with so we need a lot of resources On the other hand.

Today, we will learn how to connect a simple android client side application made with java to python flask server, after reading this article you will be able to deploy you machine learning models.You will need Android studio, The HTTP requests and responses are handled in Android using OkHttp and Pycharm IDE for python coding.

This tutorial will show you how to send a simple text in which the Android app just makes an HTTP POST message for sending it, in the other hand, the flask app will return a simple message to confirm that the connection is successful.

The implementation of this project is available on GitHub: Click here.

Enough talking, let’s get started…

Building the Layout of the Android App

Our app is designed to be simple, but this will not prevent you form improving it in the future.So I decided to make one button in the main UI, after you click this button, it will test the connection between the android app and the flask app, the message returned from the flask app will displayed as Toast notification.

You can see that we used only one button with >

After building the app user interface (UI), the next step is to implement the postRequest () method, which is responsible for message sending.

But, for doing that we must go through a small process…

First, before using OkHttp, the project must support using it.You can do that by including one line to the dependencies section of the build.gradle (app module), the line is:

Second, you must activate the using of clear text traffic in your app, in you can do that by inserting a this line to your application section in the manifest file:

It will be like this:

But we don’t forget to add the next permission in the manifest file:

without it, you application will crash.

Writing the java code of the Android App

Now, we will move to java code.

When you start reading the code, you will notice that we use the IP@ 10.0.2.2, this is just the default local address of the android emulator, and 5000 is the port number that we will use with it.You will some words like mediaType and requestBody, mediaType is just type the data that we will send such as text or image…etc, requestBody is the object that holds our message.These are some methods in the code that you must understand them:

  1. onFailure() : Called when the request couldn’t be executed due to cancellation, a connectivity problem, or timeout.
  2. onResponse() : Called when the HTTP response is successfully returned by the remote server.

The rest of the code will be easy to understand, But if you run into some problems, you can always go back to the OkHttp documentation from here.

Now, you can test the app but it will show an error message because the server is off.While we mentioned the server, let’s continue building the Python HTTP server using Flask.

Building the server-side using Flask

Flask is a micro web framework written in Python. It is classified as a microframework because it does not require particular tools or libraries.It has no database abstraction layer, form validation, or any other components where pre-existing third-party libraries provide common functions. However, Flask supports extensions that can add application features as if they were implemented in Flask itself. From Wikipedia, the free encyclopedia .

Читайте также:  Create android emulator vs code

From the picture above, you see that we created a flask app as an instance of the Flask() class, The app.route() decorator function associates a URL with a callback function.The / indicates the homepage of the server because the Android app requests will be sent to there.

The handle_request() method is responsible for return a message that confirms the connection between the client and the server.

the run() method uses the host argument for specifying the IP address. When the host is set to “0.0.0.0” , this means use the current IPv4 address. And of course, 5000 as port number.

The debug argument is for giving the permission to server for restarting itself if the code changed, otherwise you will be obligated to restart it manually to apply the new changes.

The last step: Testing

You will need an internet connection.

Now you will be able to test you app, you have to run the android app and also the python code, clicking the connect button and then you will see that it will return “Successful Connection”.

Источник

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.

Источник

Оцените статью