Android get and post requests

Android get and post requests

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 :

Читайте также:  Philips android tv настройка

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

Источник

Android get and post requests

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.

Источник

Android OkHttp3 Http Get Post Request Example

This example will show you how to use OkHttp3 to send get or post HTTP request to a web server and how to parse and display response text in an Android TextView.

1. OKHttp Characters.

  1. OkHttp3 is a third-party open-source library that is contributed by the square company. It has below characters.
  2. User-friendly API.
  3. Support http2, sharing the same socket for all requests from a machine.
  4. Built-in connection pool, support for connection reuse, and reduction of delay.
  5. Supports transparent gzip compression response.
  6. Avoid duplicate requests by caching.
  7. Automatically retry the host’s other IP and redirect automatically when the request fails.

2. Add OkHttp3 Library In build.gradle.

  1. Before you can use the OkHttp3 library, you need to add dependencies in the build.gradle file in android studio as below.
  2. You can get the most recent build library from https://github.com/square/okhttp.
  3. After adding the below code, you need to click the Sync Now link in the top right corner to sync the project.

2. Use OkHttp3 To Create HTTP Get Request Method Call Object.

  1. The below source code snippet will use the OkHttp3 library to create an HTTP GET request.

3. Use OkHttp3 To Create HTTP Post Request Method Call Object.

  1. The below source code snippet will use the OkHttp3 library to create an HTTP POST request.

4. Send Http Request Synchronously And Asynchronously.

  1. You can send HTTP GET or POST requests with OkHttp3 synchronously or asynchronously.
  2. When you send the request synchronously, you need to run the code in a child thread because the process may take a long time.
  3. When you send the request asynchronously, the system will create a child thread and run OkHttp3 code in it automatically.
Читайте также:  Play to андроид описание

5. OkHttp Get Post Request Example.

Источник

Android. GET и POST запросы к web серверу

5 сентября 2016 г. 3 Yehor Rykhnov 12678 android, java—>

Довольно часто приложению необходимо обмениваться информацией с сервером, для этого используется HTTP или HTTPS протокол. Рассмотрим простой пример запроса к серверу и получение ответа от него.

Запросы к web серверу нужно выполнять в отдельном потоке.

Подготовка

Установим в манифесте разрешение на работу с интернетом:

Работа с GET запросом

Для передачи спец символов (например: !»№;%?()) необходимо их преобразовать с помощью URLEncoder:

Работа с POST запросом

Если у вас есть вопросы или предложения по улучшению кода описанного в статье пишите в комментариях.
Я всегда открыт к конструктивному диалогу

Рекомендуемые

Комментарии

Для того, чтобы работал DefaultHttpClient — нужно установить бибилотеку apache.http. Для этого, в Android Studio:
1. Открываем Build->Edit Libraries and Dependencies->Dependencies.
2. Нажимаем на плюсик (+)
3. Выбираем Library Dependency
4. В поле поиска пишем org.apache.http и нажимаем «Enter» или жмем на кнопку поиска
Должно найти библиотеку org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2
5. Выбираем ее.
6. Жмем «Ok»

Если хотим тестить на локальном сервере — обращаемся к локальному хосту по ip. К хосту привязываем ip сетевой карты.

Подскажите плиз, как написать POST для https?

Источник

How to send HTTP request GET/POST in Java

By mkyong | Last updated: October 11, 2019

Viewed: 2,490,821 (+1,406 pv/w)

In this article, we will show you a few examples to make HTTP GET/POST requests via the following APIs

  • Apache HttpClient 4.5.10
  • OkHttp 4.2.2
  • Java 11 HttpClient
  • Java 1.1 HttpURLConnection (Not recommend)

1. Apache HttpClient

In the old days, this Apache HttpClient is the de facto standard to send an HTTP GET/POST request in Java.

2. OkHttp

This OkHttp is very popular on Android, and widely use in many web projects, the rising star.

3. Java 11 HttpClient

In Java 11, a new HttpClient is introduced in package java.net.http.*

The sendAsync() will return a CompletableFuture , it makes concurrent requests much easier and flexible, no more external libraries to send an HTTP request!

4. HttpURLConnection

This HttpURLConnection class is available since Java 1.1, uses this if you dare рџ™‚ Generally, it’s NOT recommend to use this class, because the codebase is very old and outdated, it may not supports the new HTTP/2 standard, in fact, it’s really difficult to configure and use this class.

The below example is just for self reference, NOT recommend to use this class!

References

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Maybe consider using a StringBuilder instead of the StringBuffer?

Thanks, article is updated.

very helpfull Thanks !!

Thank for Sharing this post with us. Very Helpfull and usefull Information. Hope you keep it up in future also by providing informative post.This Post is very much handy.Best of Luck & Cheers.
Thank You

I just copied the post method u’ve created and wanted to use it somewhere the same way as you did. It is just like your class but without the get() thing

Источник

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