Android retrofit post file

Upload file in Android Java with retrofit 2

Nov 13, 2019 · 4 min read

In this article, we will implement a function upload file with Retrofit2 for android. Retrofit2 is one of the most popular network request libraries for android.

Retrofit

Annotations on the interface methods and its parameters indicate how a request will be handled. Request Method Every…

1. Add retrofit 2 to gradle file (app level).

We also add Gson package which is used to parse JSON to Object when we get JSON return from API and of course we can convert a java object to JSON when we send post to the server.

2. Create Retrofit Instance

As you can see we just declare one base API endpoint at the top of the class.

in this case, I get value from the grade file config, but you can change with your API endpoint. Then we create a retrofit instance, I also added a connection timeout is 60 s because the default of Retrofit time out is 10 second so when you upload a large size, time out can occur.

3. Create an interface to upload file

In this code, we will define a request which is needed to map with API, what type if request POST, GET or PUT. What is the parameter and API endpoint.

As you can see, we just declare these parameter

Please make sure that you are using HTTPS if you are using HTTP Retrofit2 will throw the error.

in this interface, we are using POST method to send a file to the server

Luckily, Retrofit2 is supported to send a cookie to the server site. As you know almost API nowadays use token to validate user in some case, we can use a cookie. In my case, I have used cookies so I add cookies here.
You can create a cookie as String and just add to header.

4. Post Parameters, upload the file and handle the response

This is the most important things, we need to send a file to the server. In this case, we are uploading files so we will `MultipartBody`

And next is the body, you can send the body as JSON or text.

4. Upload the file

This is the way we create a request network from our main controller.

As the top line, we just initiated service with a retrofit client

Next, creating parameters and pass these values to interface

Finally, catch the callback response from the server, in this callback. If return success we will handle at the function `onResponse` else failed we will handle at `onFailure`

Bonus:

It is very important for debugging some cases when we must to know what is the api response. In some cases, the response can be not a json format instead of it is an HTML page, how we know what is the response? Fortunately, we can use the library interceptor

add interceptor to gradle app file, I got some issue when building the project, maybe you need to clean project and rebuild again.

Add log to Retrofit client

we can use ‘ ProgressDialog’ to let the user know that the upload is processing. In order to user ProgressDialog, just declare a process dialog before call API and dismiss it when finishing upload file

Then just dismiss the dialog after done calling.

Источник

Используем Retrofit 2 в Android-приложении

Retrofit — это известная среди Android-разработчиков библиотека для сетевого взаимодействия, некоторые даже считают её в каком-то роде стандартом. Причин для такой популярности масса: библиотека отлично поддерживает REST API, легко тестируется и настраивается, а запросы по сети с её помощью выполняются совсем просто. В этой статье я покажу вам, как настроить и использовать Retrofit, чтобы реализовать работу с сетью в вашем приложении.

Настройка Retrofit

Добавьте следующую зависимость в файл build.gradle :

Мы будем использовать Gson для преобразования JSON в POJO. Retrofit предоставляет зависимость, которая автоматически конвертирует JSON в POJO. Для этого добавьте ещё одну зависимость в файл build.gradle :

Если в вашем приложении ещё не разрешена работа с сетью, то обязательно добавьте соответствующуу строку в файл AndroidManifest :

После того, как зависимости добавлены, нам необходимо написать код для настройки библиотеки Retrofit.

Создайте класс с именем NetworkService :

Этот класс должен быть singleton-объектом, поэтому объявите статическую переменную и функцию, которая создаёт и возвращает переменную того же типа, что и класс. Если вы не знаете, как работает данный паттерн, то ознакомьтесь с этой статьёй, в которой есть примеры реализации на языке Java.

Для тестирования мы используем JSONPlaceholder, который предоставляет фейковый онлайн REST API для разработчиков:

Теперь мы объявим и инициализируем Retrofit в конструкторе NetworkService :

Читайте также:  Антивирус касперского андроид 4pda

Настройка завершена, теперь нам нужно определить конечные точки, которые будут возвращать данные.

Добавление конечных точек

Создайте интерфейс с именем JSONPlaceHolderApi :

На сайте JSONPlaceHolder URL /posts/id — это конечная точка, которая возвращает сообщение с соответствующим идентификатором. Данная конечная точка принимает GET-запрос и возвращает данные в формате JSON в следующем виде:

Сначала мы создадим соответствующий POJO для JSON-ответа:

Как вы видите, это простой POJO-класс. Переменные мы аннотировали с помощью @SerializedName() , передав туда имя. Эти имена фактически являются ключами в возвращаемых из API JSON-данных, поэтому вы можете как угодно изменять имя переменной, но убедитесь, что имя, переданное в аннотацию @SerializedName() , точно присутствует в JSON.

В интерфейсе, созданном выше, определите конечные точки с требуемыми параметрами:

Поскольку мы отправляем GET-запрос, нам нужно применить к методу аннотацию @GET , внутри которой находится конечная точка, на которую мы хотим отправить запрос. Как вы видите, мы не добавляем полный URL, т.к. Retrofit автоматически возьмёт BASE_URL , переданный в класс NetworkService , и добавит его к остальной части URL-адреса.

Возвращаемый тип метода называется Call

. Call — это класс, предоставляемый непосредственно самой библиотекой. И все методы в интерфейсе должны возвращать значения этого типа. Это generic-класс, принимающий в себя тип объекта, который мы хотим конвертировать в JSON. Мы передали Post , т.к. это именно тот объект, в который хотим преобразовать JSON-ответ. В параметры мы передали целое число и аннотировали его с помощью @Path , внутри которого записали id . Retrofit возьмёт это значение и в конечной точке заменит на него . Таким образом, если мы передадим значение 1 в качестве параметра, то конечная точка будет выглядеть так — /posts/1 , если передадим значение 10, то конечная точка получится — /posts/10 .

Теперь нам нужно, чтобы Retrofit предоставил реализацию интерфейса JSONPlaceHolderApi . Для этого используем метод create() :

Далее нужно получить JSONPlaceHolderApi из NetworkService и отправить запрос:

Возвращённый объект Call содержит метод с именем enqueue , который принимает в качестве параметра Callback . В onResponse мы получаем результат Response

, содержащий возвращённый с сервера объект Post . Чтобы получаем сам объект Post , используем метод response.body() . Остальная часть кода понятна без дополнительных пояснений.

Отправка различных типов запросов

В API JSONPlaceHolder есть много разных конечных точек, которые можно использовать.

Получение списка сообщений

Для получения списка всех сообщений мы изменили конечную точку и возвращаемый тип функции.

Отправка запроса с параметром

Если вы хотите отправить запрос с параметром, то нужно всего лишь использовать аннотацию @Query() для соответствующего параметра в методе:

Поэтому если мы передадим значение 6 в параметре метода, то конечная точка будет следующей — /posts?userId=6 .

Отправка POST запроса

Для отправки POST-запроса нужно просто изменить аннотацию метода.

Чтобы сформировать тело запроса для данного метода, мы используем аннотацию @Body для передаваемого параметра. Retrofit будет использовать Gson для конвертации @Body в JSON.

Существует ещё несколько различных типов запросов, которые вы можете использовать, но это уже тема для отдельной статьи.

Перехват запросов

Retrofit предоставляет способ перехвата запросов и их логирования в Logcat. Давайте настроим перехватчик и посмотрим на эту магию. Добавьте следующую зависимость в файл build.gradle :

Обновите класс NetworkService таким образом:

Теперь, когда вы отправляете или получаете запрос, все его данные, включая URL, заголовки, тело, будут выведены в лог:

На этом наша статья заканчивается. Код для этого проекта вы можете найти на GitHub.

Источник

Retrofit 2 — How to Upload Files to Server

Moonshoot

Moonshoot is a
Student Feature.

The previous tutorials guided you through various use cases of Retrofit and showed you opportunities to enhance the app with Retrofit’s built-in functionality. This tutorial will show you how to upload a file to a backend server using the second major release of Retrofit, namely Retrofit 2.

Retrofit Series Overview

Getting Started and Creating an Android Client

Basics of API Description

Creating a Sustainable Android Client

URL Handling, Resolution and Parsing

How to Change API Base Url at Runtime

Multiple Server Environments (Develop, Staging, Production)

Share OkHttp Client and Converters between Retrofit Instances

Upgrade Guide from 1.9

Beyond Android: Retrofit for Java Projects

How to use OkHttp 3 with Retrofit 1

  1. Getting Started and Creating an Android Client
  2. Basics of API Description
  3. Creating a Sustainable Android Client
  4. URL Handling, Resolution and Parsing
  5. How to Change API Base Url at Runtime
  6. Multiple Server Environments (Develop, Staging, Production)
  7. Share OkHttp Client and Converters between Retrofit Instances
  8. Upgrade Guide from 1.9
  9. Beyond Android: Retrofit for Java Projects
  10. How to use OkHttp 3 with Retrofit 1

Synchronous and Asynchronous Requests

Send Objects in Request Body

Add Custom Request Header

Manage Request Headers in OkHttp Interceptor

Dynamic Request Headers with @HeaderMap

Multiple Query Parameters of Same Name

Optional Query Parameters

Send Data Form-Urlencoded

Send Data Form-Urlencoded Using FieldMap

How to Add Query Parameters to Every Request

Add Multiple Query Parameter With QueryMap

How to Use Dynamic Urls for Requests

Constant, Default and Logic Values for POST and PUT Requests

Reuse and Analyze Requests

Optional Path Parameters

How to Send Plain Text Request Body

Customize Network Timeouts

How to Trust Unsafe SSL certificates (Self-signed, Expired)

Dynamic Endpoint-Dependent Interceptor Actions

How to Update Objects on the Server (PUT vs. PATCH)

How to Delete Objects on the Server

  1. Synchronous and Asynchronous Requests
  2. Send Objects in Request Body
  3. Add Custom Request Header
  4. Manage Request Headers in OkHttp Interceptor
  5. Dynamic Request Headers with @HeaderMap
  6. Multiple Query Parameters of Same Name
  7. Optional Query Parameters
  8. Send Data Form-Urlencoded
  9. Send Data Form-Urlencoded Using FieldMap
  10. How to Add Query Parameters to Every Request
  11. Add Multiple Query Parameter With QueryMap
  12. How to Use Dynamic Urls for Requests
  13. Constant, Default and Logic Values for POST and PUT Requests
  14. Cancel Requests
  15. Reuse and Analyze Requests
  16. Optional Path Parameters
  17. How to Send Plain Text Request Body
  18. Customize Network Timeouts
  19. How to Trust Unsafe SSL certificates (Self-signed, Expired)
  20. Dynamic Endpoint-Dependent Interceptor Actions
  21. How to Update Objects on the Server (PUT vs. PATCH)
  22. How to Delete Objects on the Server
Читайте также:  Яндекс карты для андроид самсунг

Ignore Response Payload with Call

Receive Plain-String Responses

Crawl HTML Responses with jspoon (Wikipedia Example)

Loading Data into RecyclerView and CardView

  1. Ignore Response Payload with Call
  2. Receive Plain-String Responses
  3. Crawl HTML Responses with jspoon (Wikipedia Example)
  4. Loading Data into RecyclerView and CardView

Introduction to (Multiple) Converters

Adding & Customizing the Gson Converter

Implementing Custom Converters

How to Integrate XML Converter

Access Mapped Objects and Raw Response Payload

Supporting JSON and XML Responses Concurrently

Handling of Empty Server Responses with Custom Converter

Send JSON Requests and Receive XML Responses (or vice versa)

Unwrapping Envelope Responses with Custom Converter

Wrapping Requests in Envelope with Custom Converter

Define a Custom Response Converter

  1. Introduction to (Multiple) Converters
  2. Adding & Customizing the Gson Converter
  3. Implementing Custom Converters
  4. How to Integrate XML Converter
  5. Access Mapped Objects and Raw Response Payload
  6. Supporting JSON and XML Responses Concurrently
  7. Handling of Empty Server Responses with Custom Converter
  8. Send JSON Requests and Receive XML Responses (or vice versa)
  9. Unwrapping Envelope Responses with Custom Converter
  10. Wrapping Requests in Envelope with Custom Converter
  11. Define a Custom Response Converter

Simple Error Handling

Error Handling for Synchronous Requests

Catch Server Errors Globally with Response Interceptor

How to Detect Network and Conversion Errors in onFailure

Log Requests and Responses

Enable Logging for Development Builds Only

Log Network Traffic with Stetho and Chrome Developer Tools

Using the Log Level to Debug Requests

Analyze Network Traffic with Android Studio Profiler

Debug and Compare Requests with RequestBin

  1. Log Requests and Responses
  2. Enable Logging for Development Builds Only
  3. Log Network Traffic with Stetho and Chrome Developer Tools
  4. Using the Log Level to Debug Requests
  5. Analyze Network Traffic with Android Studio Profiler
  6. Debug and Compare Requests with RequestBin

Introduction to Call Adapters

Custom Call Adapter to Separate OnResponse Callback

How to Integrate RxJava 1.x Call Adapter

How to Integrate RxJava 2.x Call Adapter

How to Integrate Guava Call Adapter

Custom Call Adapter to Separate Network and Gson Errors

  1. Introduction to Call Adapters
  2. Custom Call Adapter to Separate OnResponse Callback
  3. How to Integrate RxJava 1.x Call Adapter
  4. How to Integrate RxJava 2.x Call Adapter
  5. How to Integrate Guava Call Adapter
  6. Custom Call Adapter to Separate Network and Gson Errors

Pagination Using Query Parameter

Pagination Using Link Header and Dynamic Urls (Like GitHub)

Pagination Using Range Header Fields (Like Heroku)

  1. Pagination Using Query Parameter
  2. Pagination Using Link Header and Dynamic Urls (Like GitHub)
  3. Pagination Using Range Header Fields (Like Heroku)

How to Upload Files to Server

How to Upload Multiple Files to Server

How to Upload a Dynamic Amount of Files to Server

Upload Files with Progress

Passing Multiple Parts Along a File with @PartMap

How to Download Files from Server

Download Files with Progress Updates

How to Upload Files to Server

    How to Upload Files to Server
  1. How to Upload Multiple Files to Server
  2. How to Upload a Dynamic Amount of Files to Server
  3. Upload Files with Progress
  4. Passing Multiple Parts Along a File with @PartMap
  5. How to Download Files from Server
  6. Download Files with Progress Updates
  7. How to Upload Files to Server

Basic Authentication on Android

Token Authentication on Android

OAuth on Android

Hawk Authentication on Android

How to Refresh an Access Token

  1. Basic Authentication on Android
  2. Token Authentication on Android
  3. OAuth on Android
  4. Hawk Authentication on Android
  5. How to Refresh an Access Token

Activate Response Caching (Etag, Last-Modified)

Check Response Origin (Network, Cache, or Both)

Force Server Cache Support with Response Interceptor

Support App Offline Mode by Accessing Response Caches

Analyze Cache Files

  1. Activate Response Caching (Etag, Last-Modified)
  2. Check Response Origin (Network, Cache, or Both)
  3. Force Server Cache Support with Response Interceptor
  4. Support App Offline Mode by Accessing Response Caches
  5. Analyze Cache Files

Basics of Mocking Server Responses

Customizing Network Behavior of Mocked Server Responses

Mock APIs with JsonServer

  1. Basics of Mocking Server Responses
  2. Customizing Network Behavior of Mocked Server Responses
  3. Mock APIs with JsonServer

Fluent Interface with Builders

File Upload with Retrofit 1.x

We’ve already published a tutorial on how to upload files using Retrofit 1.x . If you’re using Retrofit 1, please follow the link.

Using Retrofit 2? This tutorial is for you and please read on 🙂

Upload Files With Retrofit 2

This tutorial is intentionally separated from the already published tutorial on how to upload files with Retrofit v1, because the internal changes from Retrofit 1 to Retrofit 2 are profound and you need to understand the way Retrofit 2 handles file uploads.

Before we dive deeper into the file upload topic with Retrofit 2, let’s shortly recap the previously used functionality in v1. Retrofit 1 used a class called TypedFile for file uploads to a server. This class has been removed from Retrofit 2. Further, Retrofit 2 now leverages the OkHttp library for any network operation and, as a result, OkHttp’s classes for use cases like file uploads.

Using Retrofit 2, you need to use either OkHttp’s RequestBody or MultipartBody.Part classes and encapsulate your file into a request body. Let’s have a look at the interface definition for file uploads.

Читайте также:  Лучший голосовой переводчик для андроида

Let me explain each part of the definition above. First, you need to declare the entire call as @Multipart request. Let’s continue with the annotation for description . The description is just a string value wrapped within a RequestBody instance. Secondly, there’s another @Part within the request: the actual file . We use the MultipartBody.Part class that allows us to send the actual file name besides the binary file data with the request. You’ll see how to create the file object correctly within the following section.

Android Client Code

At this point, you’ve defined the necessary service interface for Retrofit. Now you can move on and touch the actual file upload. We’ll use the ServiceGenerator class which generates a service client. We’ve introduced the ServiceGenerator class in the creating a sustainable Android client tutorial earlier in this series.

The following code snippet shows the uploadFile(Uri fileUri) method taking the file’s uri as a parameter. If you’re starting an intent to choose a file, you’ll return within the onActivityResult() method of Android’s lifecycle. In this method, you can get the file’s uri and that’s exactly what you’ll use to upload the file within the uploadFile method.

The snippet above shows you the code to initialize the payload ( body and description ) and how to use the file upload service. As already mentioned, the RequestBody class is from OkHttp and used for the description. Its .create() method requires two parameters: first, the media type, and second, the actual data. The media type for the description can simply be OkHttp’s constant for multipart requests: okhttp3.MultipartBody.FORM . The media type for the file should ideally be the actual content-type. For example, a PNG image should have image/png . Our code snippet above figures out the content type with the getContentResolver().getType(fileUri) call and then parses the result into OkHttp’s media type with MediaType.parse() .

Besides the description, you’ll add the file wrapped into a MultipartBody.Part instance. That’s what you need to use to appropriately upload files from client-side. Further, you can add the original file name within the createFormData() method and reuse it on your backend.

Remember the Content-Type

Please keep an eye on Retrofit’s content type. If you intercept the underlying OkHttp client and change the content type to application/json , your server might have issues with the deserialization process. Make sure you’re not defining the header indicating you’re sending JSON data, but multipart/form-data .

Next: Upload Files with Progress Updates

If you upload files in the foreground and they are not small, you might want to inform the user on your actions. Ideally, you would display progress updates how much you’ve uploaded already. We’ve another tutorial on how to upload files with progress updates.

Exemplary Hapi Server for File Uploads

If you already have your backend project, you can lean on the example code below. We use a simple hapi server with a POST route available at /upload . Additionally, we tell hapi to don’t parse the incoming request, because we use a Node.js library called multiparty for the payload parsing.

Within the callback of multiparty’s parsing function, we’re logging each field to show its output.

Android client expects a return type of String , we’re sending the received information as response. Of course your response will and should look different 🙂

Below you can see the output of a successful request and payload parsing on server-side. The first null is the err object. Afterwards, you can see the fields which is only the description as part of the request. And last but not least, the file is available within the picture field. Here you see our previously defined names on client side. 20160312_095248.jpg is passed as the original name and the actual field name is picture . For further processing, access the uploaded image at path ’s location.

Server Log for Parsed Payload

Outlook

File uploads are an essential feature within up-to-date apps and you can integrate this feature within your app using Retrofit. This tutorial guided you through the necessary steps to upload a file from your Android device to your backend server.

What to expect within the next post on Retrofit? Next week you’ll learn all about how to get back logging within Retrofit 2. Stay tuned, it will be a good shot!

Still Have Questions? Get Our Retrofit Book!

All modern Android apps need to do network requests. Retrofit offers you an extremely convenient way of creating and managing network requests. From asynchronous execution on a background thread, to automatic conversion of server responses to Java objects, Retrofit does almost everything for you. Once you’ve a deep understanding of Retrofit, writing complex requests (e.g., OAuth authentication) will be done in a few minutes.

Invest time to fully understand Retrofit’s principles. It’ll pay off multiple times in the future! Our book offers you a fast and easy way to get a full overview over Retrofit. You’ll learn how to create effective REST clients on Android in every detail.

Boost your productivity and enjoy working with complex APIs.

Get Notified on New Future Studio
Content and Platform Updates

Get your weekly push notification about new and trending
Future Studio content and recent platform enhancements

Источник

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