- Android. GET и POST запросы к web серверу
- Подготовка
- Работа с GET запросом
- Работа с POST запросом
- Рекомендуемые
- Комментарии
- Android HTTP requests made easy
- Adding permissions
- Method 1: Creating custom classes
- HttpManager
- Putting it all together
- Method 2: Android Asynchronous HTTP Client
- Creating the MainActivity
- Conclusion
- Get request android studio
- 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
- Отправляем GET запрос в Android без Apache
- Simple GET request using Retrofit in Android
- Introduction
- Uses of retrofit
- Advantages of retrofit
- Disadvantages of retrofit
- Classes used in retrofit
- Prerequisites
- Step 1 – Create a new Android studio project
- Step 2 – Adding retrofit to our application
- Step 3 – Designing the UI for our application
- Step 4 — Create a model class
- Step 5 — Create a retrofit instance
- Step 6 – Define the endpoints
- Step 7 – Sending a GET request
- To wrap up
- About the author
- Want to learn more about the EngEd Program?
Android. GET и POST запросы к web серверу
5 сентября 2016 г. 3 Yehor Rykhnov 12686 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 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.
Источник
Get request 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.
Источник
Отправляем GET запрос в Android без Apache
Когда заходит разговор о работе с HTTP под Android чаще всего сразу же вспоминают библиотеку классов от Apache. При этом незаслуженно игнорируя другой не менее эффективный способ обмена данными.
Этот способ по праву можно считать если не очевидным, то, по крайней мере, хорошо известным для тех, кто программирует на Java. Однако в среде Android разработчиков он пока почему-то не получил широкого распространения.
Речь идёт о пакете java.net, который входит в состав «обычного» Java SE, но доступен также и в Android.
Для отправки запроса потребуется всего два класса из этого пакета URL и HttpURLConnection.
Вначале создадим подключение к тому ресурсу, к которому планируется оправить запрос. Для этого создадим объект класса URL и на его основе получим объект класса HttpURLConnection.
Затем собственно отправляем сам запрос и обрабатываем результат:
В чём преимущество java.net перед Apache?
- Это стандартный пакетJava.
Для его использования не требуется устанавливать или подключать каких-либо сторонних библиотек. А, писать программы с его использованием можно практически «не оглядываясь» на версию Android; - Больше возможностей контролировать процесс обмена данными.
В частности, можно без труда анализировать ответ сервера, что часто требуется при работе с RestAPI; - Более простая и компактная реализация программ для работы сHTTP.
Для того чтобы отправить даже простой запрос в библиотеке от Apache требуется работа с тремя объектами. В java.net всё сводится, по сути, к одному HttpURLConnection. При этом без ущерба для архитектуры приложения; - JavaSE и, в частности,java.net превосходно документированы.
К сожалению, этого нельзя сказать о библиотеке от Apache. Документация по ней представлена только в виде примеров, которые уже не актуальны для более новых версий.
Последнее преимущество обычно принято как-то сбрасывать со счетов. Однако про него почему-то столь же часто вспоминают, когда дело доходит до сложных или просто не тривиальных задач и все остальные способы разобраться в проблеме исчерпаны. О том насколько влияет наличие и качество документации на возможность освоения для новичков, и говорить не приходится.
Из недостатков рассматриваемого способа можно отметить только один. HttpURLConnection позволяет получить данные только в виде набора байт. Поэтому, чтобы получить ответ с сервера в виде строки требуется выполнить преобразования.
Источник
Simple GET request using Retrofit in Android
January 5, 2021
Networking is a crucial factor in mobile development. Most, if not all mobile applications incorporate networking on some level. Applications are either sending or receiving information. Initially, developers did networking on the main thread . This made applications less user-friendly since screens would “freeze”.
Networking on the main thread stopped after the Honeycomb version was released. Google then developed Volley in 2013.
Introduction
You can read my article on Volley here.
Volley offered something better: It was faster, provided better functionality, a simpler syntax, etc. Still, there was room for growth when it came to networking.
Square introduced Retrofit.
Retrofit is a type-safe HTTP networking library used for Android and Java. Retrofit was even better since it was super fast, offered better functionality, and even simpler syntax. Most developers since then have switched to using Retrofit to make API requests.
Uses of retrofit
Retrofit is used to perform the following tasks:
- It manages the process of receiving, sending, and creating HTTP requests and responses.
- It alternates IP addresses if there is a connection to a web service failure.
- It caches responses to avoid sending duplicate requests.
- Retrofit pools connections to reduce latency.
- Retrofit resolves issues before sending an error and crashing the app.
Advantages of retrofit
- It is very fast.
- It enables direct communication with the web service.
- It is easy to use and understand.
- It supports request cancellation.
- It supports post requests and multipart uploads.
- It supports both synchronous and asynchronous network requests.
- Supports dynamic URLs.
- Supports convertors.
Disadvantages of retrofit
- It does not support image loading. It requires other libraries such as Glide and Picasso .
- It does not support setting priorities.
Classes used in retrofit
- Model class — This class contains the objects to be obtained from the JSON file.
- Retrofit instance — This Java class is used to send requests to an API.
- Interface class- This Java class is used to define endpoints.
Prerequisites
- Have Android Studio installed.
- The reader should have a beginner level understanding of Java and XML.
- The reader should have basic knowledge of making network requests, JSON, and REST APIs.
Step 1 – Create a new Android studio project
Open Android Studio and Start a new Android Studio Project -> Empty Activity. Let us name the project MarvelRetrofit . Select Finish and wait for the project to build.
Step 2 – Adding retrofit to our application
Add the following dependencies to your app-level build.gradle file.
Note: One can add different convertors depending on the JSON one would like to use. The following are examples of some of the converters:
- Jackson : com.squareup.retrofit2:converter-jackson:2.1.0
- Moshi : com.squareup.retrofit2:converter-moshi:2.1.0
- Protobuf : com.squareup.retrofit2:converter-protobuf:2.1.0
- Wire : com.squareup.retrofit2:converter-wire:2.1.0
- Simple XML : com.squareup.retrofit2:converter-simplexml:2.1.0
Add internet permission to you application.
Step 3 – Designing the UI for our application
In this step, we will design the layout for our application. Since this is a simple application, we will only use a ListView to display the API’s information.
Add the following lines of code to your layout resource file:
Step 4 — Create a model class
Next, we will create a model class that will contain the objects from the JSON. For our instance, we only want to get the names of the fictional characters.
In the Java directory, right-click and select new-в†’ java class-в†’ app/src/main/java–> class. We will name our model class Results.
Add the following lines of code in Results.java :
Note: The SerializedName annotation should always display the exact name of an object in the JSON file.
Step 5 — Create a retrofit instance
This Java class is used to send requests to an API. We specify the URL that contains the data required and use the Retrofit Builder class.
In the Java directory, right-click and select new-в†’ java class-в†’ app/src/main/java-в†’class. We shall name our class, RetrofitClient.
Add the following lines of code to the RetrofitClient.java :
Step 6 – Define the endpoints
Endpoints usually are defined inside an Interface class. An endpoint refers to the path where information is obtained. Our endpoint is ‘marvel’. Since our aim is to obtain information from the API, we will be using the @GET annotation since we are making a Get request.
Next we will have a call object that will return the information from the API.
In the Java directory, right-click and select new–> java class–> app/src/main/java–>class. We will name our Interface class Api.
Add the following lines of code in Api.java :
Step 7 – Sending a GET request
In this step, we will call each of the API endpoints defined in our Interface class. The interface class will enable the information from the API to be displayed in our ListView .
Finally, we will have an onFailure method, that will display a Toast message if the information is not successfully loaded into the ListView .
Add the following lines of code to your MainActivity.java
Let’s run our application.
To wrap up
We have learned that networking is a crucial factor in mobile application development. We have learned how to use Retrofit and its advantages and disadvantages. Did you know that Retrofit takes 312ms to carry out one discussion? That is super fast.
Check out other ways to use Retrofit in their official documentation. You can access this tutorial’s code on GitHub. You can also download the sample APK on Google Drive.
Peer Review Contributions by: Peter Kayere
About the author
Briana is an undergraduate student pursuing a degree in Electronics and Computer Engineering. Briana loves developing mobile applications, technical writing, and following up on UI/UX trends. She enjoys traveling and gardening.
Want to learn more about the EngEd Program?
Discover Section’s community-generated pool of resources from the next generation of engineers.
Источник