Android studio post request

Android HTTP requests made easy

If you’ve ever had to make an HTTP network request in Android, you know what a pain it can be. Making Android HTTP requests usually involves writing a lot of boilerplate code. You could make things a bit easier by creating some custom classes, but it can still be tedious.

In this tutorial I will show you how to make network requests using two different methods. The first method involves creating custom classes, which will aid in code reusability. The second method involves adding a library called the Android Asynchronous Http Client by loopj. This library will greatly reduce the amount of code you will need to write.

In addition, we will be making a network request to the BitcoinAverage API which returns a JSON string. You will learn how to handle the JSON string, both with and without the use of the Android Asynchronous Http Client library.

This tutorial is for those who:

  • are comfortable with the Android development environment;
  • want to learn an easier way to make HTTP requests in Android.

Note: you should also be comfortable with Java and how Object-Orientation works in Java.

Adding permissions

This step is relevant to both methods. Navigate to your AndroidManifiest.xml file and add the following permission before the tag:

Method 1: Creating custom classes

The first class we will be creating is called the RequestPackage class. This class will accept three important values when making HTTP requests. First, it will receive the URL. Next, it will receive the request method (POST or GET). Last, it will receive any values that the server might need (e.g. product_id). The request package will then be sent to the HttpManager class that we will create later.

Create a class called RequestPackage and add the following code to the class:

HttpManager

Next, we will create the HttpManager class. As mentioned earlier, the HttpManager receives the RequestPackage that we created in the previous section. The HttpManager is responsible for making the actual request and receiving the response from the server.

Create a class called HttpManager and add the following code to it:

Читайте также:  Как отключить всплывающие окна сообщений андроид

Putting it all together

Finally, we can use the code we just implemented. Here we will be putting everything together within the MainActivity. We will have to create a private class within the MainActivity and we will call it Downloader.

The Downloader class is an AsyncTask, which is required when making network requests in Android. If you try to make network requests outside an AsyncTask, your UI will freeze until it gets the HTTP response from the server.

Create an activity called MainActivity and add the following code:

And we are done. The amount of code we needed to write in order to get those three small pieces of information is a lot. It gets even worse if you want to use something like a RecyclerView. That would involve creating an adapter, which would significantly increase the amount of code we need to write.

In the next section, I will show you how to do the same thing by making use of the Android Asynchronous Http Client.

Method 2: Android Asynchronous HTTP Client

Navigate to the app/build.gradle file and enter the code below in the dependencies section:

Android Studio will ask if you would like to sync your project. You should do this and the dependencies will be downloaded.

Creating the MainActivity

Next, you will need to add the code below to the MainActivity:

Run your app and, voila, you’re done.

Conclusion

Well done! You have completed this tutorial. As you can see, the amount of code needed when working with the Android Asynchronous Http Client is far less than making HTTP requests using no library.

You now have a choice to make: do you prefer method 1 or method 2?

To find out more about the Android Asynchronous Http Client, please visit: http://loopj.com/android-async-http/

To view and/or clone a similar project to the one in this tutorial – that also uses the Android Asynchronous Http Client – please visit: https://github.com/londonappbrewery/bitcoin-ticker-android-citispy

To find out more about the BitcoinAverage API, please visit: https://bitcoinaverage.com/

Find out more about our Certified Mobile Developer Bootcamp. You will cover the following modules: Java Programming Essentials, Introduction to Mobile Development and Advanced Mobile Developer.

This article was contributed by Yusuf Isaacs.

Editor’s note: This was post was originally published November 14th, 2017 and has been updated February 18th, 2019.

Источник

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.
Читайте также:  Device model identifier android

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.

5. OkHttp Get Post Request Example.

Источник

How To Send A POST Request In Android

Android Tutorials

There are multiple networking libraries and classes available for Android that can send POST requests, but this tutorial covers the use of Volley, Google’s library.

Volley makes it easy to send HTTP ‘POST’ requests from your Android tablet or smartphone. To make it even easier, Android Studio speeds up the coding process by generating some of the POST request code for you. As is the case with all libraries, Volley doesn’t suit all applications. Please read more about the strengths and weaknesses of each library. You can use Eclipse, but i’d highly recommend Android Studio for its stability.

There are various ways to send a POST request using Volley, but this article explains how to use the StringRequest with a HashMap. If you need to send a POST request with JSON data using Volley, you can do so with a JsonObjectRequest, and if you need to send or receive a JSON array in your POST request, you can use a JsonArrayRequest.

First, you need to add the Volley library as a dependency of your project, as shown in the video below.

Then import the Volley and HashMap library into the Activity you’re sending the POST request from.

Now you can begin coding your HTTP POST request.

Example Code: Sending POST Data In Android

Declare a RequestQueue:

Create a StringRequest (you need to include the ‘http’ in the url, otherwise your POST request will fail):

Источник

Сделать POST-запрос к Api в Android Studio

Я пытаюсь сделать запрос POST для API, который я создал в Visual Studio. API работает, и мне наконец-то удалось найти код, который позволяет мне подключаться к нему (и это не рекомендуется). Проблема в том, что этот код был создан для запроса GET, а мне нужно сделать POST. Я создал два блока, в которые вставляю данные, которые хочу передать (utente, пароль), и создал кнопку, которая берет данные из boxex и преобразует их в строку.

Читайте также:  Быстрая оплата картой с андроид

Я уже пробовал искать множество примеров и руководств, которые показывают, как сделать запрос POST, но большинство из них очень старые и больше не работают в Android Studio, или, по крайней мере, я не могу заставить их работать.

Теперь, это функция, которая должна отправлять данные, я не касался кода, так как не знаю, что изменить, кроме метода запроса.

Может кто-нибудь объяснить мне, как взять данные и отправить их как объект JSON, который имеет

Ключи = пользователь, пароль

Values = utente, password (значения взяты из двух упомянутых выше полей)

Спасибо всем, кто хочет помочь мне, и я надеюсь, что обращение за такой большой помощью не противоречит правилам сайта.

Я использую Волей, так как это не так сложно и потому что, кажется, работает.

Используя метод GET, он показывает, что существующий json с сообщением не может быть преобразован в объект JSON (мне все равно, это просто подтверждение того, что он подключается к API)

Используя метод POST, он выдает ErrorResponse в конце (источник еды не отвечает)

РЕДАКТИРОВАТЬ: добавлен метод OnCreate, поскольку мне нужно возвращение StringRequest

РЕДАКТИРОВАТЬ. Я следовал предложенному ответу, но он не работает .

Полученный код показан ниже, но я получаю OnErrorResponse, я не думаю, что это проблема с API, потому что при попытке получить ответ GET он дает мне выходной массив json, поэтому я думаю, что это проблема с кодом.

Источник

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

5 сентября 2016 г. 3 Yehor Rykhnov 12668 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 сетевой карты.

Источник

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