- Android OkHttp3 Http Get Post Request Example
- 1. OKHttp Characters.
- 2. Add OkHttp3 Library In build.gradle.
- 2. Use OkHttp3 To Create HTTP Get Request Method Call Object.
- 3. Use OkHttp3 To Create HTTP Post Request Method Call Object.
- 4. Send Http Request Synchronously And Asynchronously.
- 5. OkHttp Get Post Request Example.
- Android. GET и POST запросы к web серверу
- Подготовка
- Работа с GET запросом
- Работа с POST запросом
- Рекомендуемые
- Комментарии
- Android GET and POST Request
- 6 Answers 6
- POST запросы в Android. Как?
- 4 ответа 4
- Make an HTTP request with android
- 12 Answers 12
- UPDATE
- Original Answer
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.
- OkHttp3 is a third-party open-source library that is contributed by the square company. It has below characters.
- User-friendly API.
- Support http2, sharing the same socket for all requests from a machine.
- Built-in connection pool, support for connection reuse, and reduction of delay.
- Supports transparent gzip compression response.
- Avoid duplicate requests by caching.
- Automatically retry the host’s other IP and redirect automatically when the request fails.
2. Add OkHttp3 Library In build.gradle.
- Before you can use the OkHttp3 library, you need to add dependencies in the build.gradle file in android studio as below.
- You can get the most recent build library from https://github.com/square/okhttp.
- 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.
- 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.
- The below source code snippet will use the OkHttp3 library to create an HTTP POST request.
4. Send Http Request Synchronously And Asynchronously.
- You can send HTTP GET or POST requests with OkHttp3 synchronously or asynchronously.
- When you send the request synchronously, you need to run the code in a child thread because the process may take a long time.
- When you send the request asynchronously, the system will create a child thread and run OkHttp3 code in it automatically.
5. OkHttp Get Post Request Example.
Источник
Android. GET и POST запросы к web серверу
5 сентября 2016 г. 3 Yehor Rykhnov 12659 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 сетевой карты.
Источник
Android GET and POST Request
Can anyone point me to a good implementation of a way to send GET and POST Requests. They are alot of ways to do these, and i am looking for the best implementation. Secondly is there a generic way to send both these methods rather then using two different ways. After all the GET method merely has the params in the Query Strings, whereas the POST method uses the headers for the Params.
6 Answers 6
You can use the HttpURLConnection class (in java.net) to send a POST or GET HTTP request. It is the same as any other application that might want to send an HTTP request. The code to send an Http Request would look like this:
A GET request will look a little bit different, but much of the code is the same. You don’t have to worry about doing output with streams or specifying the content-length or content-type:
I prefer using dedicated class to do GET/POST and any HTTP connections or requests. Moreover I use HttpClient to execute these GET/POST methods.
Below is sample from my project. I needed thread-safe execution so there is ThreadSafeClientConnManager .
There is an example of using GET (fetchData) and POST (sendOrder)
As you can see execute is general method for executing HttpUriRequest — it can be POST or GET.
EDIT
The execute method is public because sometimes I use custom (or dynamic) GET/POST requests.
If you have URL object you can pass to execute method:
Источник
POST запросы в Android. Как?
Решил попробовать пописать под Android, соответственно появилось очень большое количество вопросов. Кому не трудно ответьте пожалуйста.
Пытаюсь сделать, чтобы приложение работало с неким API, общение с помощью json , но у меня не получается написать класс, как например на шарпе, в который я передаю адрес, параметры и выполняю POST запрос, например как здесь https://stackoverflow.com/questions/4015324/http-request-with-post.
Насколько я понял приложение на Android не может выполнить POST запрос из обычного метода, нужно использовать AsyncTask<> — тут я вообще ничего не понял, начиная от самого синтаксиса, а именно doInBackground(String. params) — String. это перечисления параметров при вызове метода типа doInBackground(str1, str2, str3) или как?
В общем я не прошу написать за меня готовый код, прошу помочь понять принцип как работать с POST запросами в Android, хотя бы один конкретный пример: отправка POST (json) и получение ответа так же в json и немного теории, пжлст)).
как я понял первое это тип входящего значения, второй тип промежуточного значения(. ), третий это тип возвращаемого значения, верно? Что есть промежуточное значение?
4 ответа 4
AsyncTask лучше один раз попробовать, и потом забыть про них. То же самое касается и HttpUrlConnection . В настоящий момент основной библиотекой для взаимодействия с Rest сервером в Android считается Retorofti. На официальном сайте есть примеры. Так же их не мало и на сторонних ресурсах, например здесь. Приведу лишь пример POST запроса.
Для этого нам потребуется класс-модель, в которую преобразуется полученный от сервера Json, класс-модель для тела запроса и интерфейс с методом аннотированным специальной анотацией.
Допустим сервер имеет метод, который добавляет почтовые адреса пользователю, и возвращает какую то информацию о статусе операции. В теле запроса сервер принимает обычный массив из строк, а результат возвращает в виде Json.
Сначала создаем модель ответа сервера(поля объявлены как public с целью уменьшения кода, в реальном приложении лучше использовать private + get/set методы):
Теперь создаем интерфейс, через который будет происходить взаимодействие с сервером.
Аннотация над методом означает что будет выполнен POST запрос, аннотация @Body указывает на то, что этот объект должен быть передан в теле запроса.
Далее необходимо создать сервера. Делается это так:
Вызывая метод enqueue() вы говорите что бы запрос выполнился асинхронно. В конце результат придет в переданный callback где его можно обработать. Вот в принципе и все. Данная библиотека не ограничивается одним лишь POST запросом, она умеет делать все, что нужно для разработки клиент-серверного приложения.
Источник
Make an HTTP request with android
I have searched everywhere but I couldn’t find my answer, is there a way to make a simple HTTP request? I want to request a PHP page / script on one of my websites but I don’t want to show the webpage.
If possible I even want to do it in the background (in a BroadcastReceiver)
12 Answers 12
UPDATE
This is a very old answer. I definitely won’t recommend Apache’s client anymore. Instead use either:
Original Answer
First of all, request a permission to access network, add following to your manifest:
Then the easiest way is to use Apache http client bundled with Android:
If you want it to run on separate thread I’d recommend extending AsyncTask:
You then can make a request by:
unless you have an explicit reason to choose the Apache HttpClient, you should prefer java.net.URLConnection. you can find plenty of examples of how to use it on the web.
Note: The Apache HTTP Client bundled with Android is now deprecated in favor of HttpURLConnection. Please see the Android Developers Blog for more details.
Add to your manifest.
You would then retrieve a web page like so:
I also suggest running it on a separate thread:
See the documentation for more information on response handling and POST requests.
The most simple way is using the Android lib called Volley
Volley offers the following benefits:
Automatic scheduling of network requests. Multiple concurrent network connections. Transparent disk and memory response caching with standard HTTP cache coherence. Support for request prioritization. Cancellation request API. You can cancel a single request, or you can set blocks or scopes of requests to cancel. Ease of customization, for example, for retry and backoff. Strong ordering that makes it easy to correctly populate your UI with data fetched asynchronously from the network. Debugging and tracing tools.
You can send a http/https request as simple as this:
In this case, you needn’t consider «running in the background» or «using cache» yourself as all of these has already been done by Volley.
Источник