File to requestbody android

Содержание
  1. File to requestbody android
  2. Android OkHttp Example
  3. OkHttp Supports Http/2
  4. Features of OkHttp.
  5. Add Library to Project
  6. Add Permission to Manifest
  7. Android OkHttp Examples
  8. Android OkHttp Get Example
  9. Android OkHttp Get Request With Query String Example
  10. Android OkHttp Post Example
  11. Android OkHttp POST JSON Example
  12. Android OkHttp Headers Example
  13. Android OkHttp Async Call
  14. Android OkHttp Multipart Example
  15. Android OkHttp Example Code
  16. Activity
  17. Layout
  18. About
  19. Upload Files to Server using Service in Android
  20. Step for implementation
  21. 6. Write a File Provider
  22. 7. Finally, Open the Activity (MainActivity) add do below operation
  23. Upload file in Android Java with retrofit 2
  24. Retrofit
  25. Annotations on the interface methods and its parameters indicate how a request will be handled. Request Method Every…
  26. 1. Add retrofit 2 to gradle file (app level).
  27. 2. Create Retrofit Instance
  28. 3. Create an interface to upload file
  29. 4. Upload the file
  30. Bonus:
  31. Android Upload File to Server with Progress
  32. Objective
  33. Android Upload File to Server with Progress
  34. Prerequisite
  35. 1. Create a new Project
  36. 2. Add Dependency
  37. 3. Add Uses Permission
  38. 4. Create a FileProvider
  39. 5. Create a Contract for Image for developing MVP design pattern
  40. 6. Prepare Image Presenter
  41. 7. Write a Contract for File Uploading
  42. 8. Furthermore, Define File Uploader Model
  43. 9. Create a presenter for File Uploading
  44. 10. Create an API interface for using Retrofit lib
  45. 11. Create Retrofit instance
  46. 12 . Open build.gradle file define BASE_URL like below
  47. 13. Open activity_main.xml and create a profile view using below code
  48. 14. Open MainActivity and do following this
  49. Bind view with activity using Butterknife

File to requestbody android

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.

Источник

Upload Files to Server using Service in Android

In the previous blog, I have learned, File uploading to the server from an activity. Now In this article, I’m going to explain how to upload file to the server using Android Service.

In earlier, Normally We use IntentService to perform background task, it is an advanced form of background service in android. That creates a separate thread to perform background operation. But Android Oreo imposed some limitation of background execution. I have written a separate article on it you can read here. So IntentService does not work in Oreo devices and onward while app is in background . In Oreo Android introduced JobIntentService for performing background. It is the modern way of using the background service to perform background task(that run in both cases while app is foreground or background). I have written also a separate article on Working with JobIntentService also. Now we will use JobIntentService for file uploading.

Step for implementation

  1. Create a new class and extends JobIntentService.
  2. Now override the onHandleWork() methods.
  3. Setup Retrofit instance and Expose API file upload API
  4. Place file upload logic in onHandleWork()
  5. Create a local BroadCastReceiver() that update the result of service in activity
  6. Now expose enqueueWork() to start this service
  7. Open MainActivity and starts the JobIntentService
  8. We have to pass file path with Intent so write a below code for getting file from camera and intent.
  9. Open AndroidManifest and add followings code
Upload Files to Server using Service (Demo App)

Let’s implements above one by one.

1. Create a new class and extends JobIntentService

Create a new project with Basic Template. open app/build .gradle add the dependency

After that create a new class in named is FileUploadService and extends JobIntentService. Then override the onHandleWork() methods.

2. Setup Retrofit instance and Expose API file upload API

Create a interface named RestApiService and expose file upload API

Now create instances of Retrofit like this

3. Create a utility class named is CountingRequestBody
4.. Open the FileUploadService and do following operation

Furthermore, open the FileUploadService again and call the API likes below

  • Place file upload logic in onHandleWork()
  • Create a local BroadCastReceiver() that updates the result in activity
  • Now expose enqueueWork() to start this service
Читайте также:  Router scan для андроид 4pda

The complete FileUploadService is looks like this

4.1 Declare service inside the Manifest
  • For Pre-Oreo devices => We have to set uses permission – WAKE_LOCK permission
  • For Oreo device => you have to declare android.permission.BIND_JOB_SERVICE
5. Open activity_main.xml and add below code

6. Write a File Provider

In this demo, we will capture image from camera and gallery with the help of FileProvider. I have written a separate article on capturing image from camera/gallery using FileProvider. I would like to suggest Read this article more clarity.

6.1 Go to res => xml => create a new xml file named is file_provider_path.xml and paste that code

6.2 Now open the AndroidManifest.xml and declare file provider inside the application tag

6.3 Declare storage and camera permission in manifest

7. Finally, Open the Activity (MainActivity) add do below operation

  • We are using Dexter for using permission on run time. So Expose requestStoragePermission() for requesting permission
  • Create methods for preparing intent for camera and gallery names is startCamera() and chooseGallery ()
  • Handle callback result in onActivityResult()
  • Register and UnRegister local BroadcastReceiver

Final code of Activity looks like below

I’m new in Android so If you have any queries or suggestions, feel free to ask them in the comment section below. Happy Coding 🙂

Источник

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

Читайте также:  You are surrounded для android

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.

Источник

Android Upload File to Server with Progress

In this article, I’m going to explain how to upload file to server using Retrofit with ProgressBar. File uploading is very common functionality so now we brought a complete solution with the latest technology. In this demo, we are using Retrofit with RxJava for file uploading in the MVP design pattern.

Objective

  • Get image from Camera/Gallery using FileProvider and show preview on ImageView
  • Upload selected to server with progress and without ProgressBar

Android Upload File to Server with Progress

Prerequisite

To better understanding this article, You need to have basic knowledge of the following topics.

  • You have to the idea about android Camera utilities
  • Have basic knowledge of FileProvider
  • How to use retrofit with RxJava
  • Have working experience of the MVP Design Pattern.

Read our previous article that give you idea about Camera, FileProvider and MVP

1. Create a new Project

Open Android Studio and create a new project with BasicActivity template in Android

2. Add Dependency

2.1 Now open build.gradle file and add following dependency
2.2 Now go to parent build.gradle (Project level build.gradle) add all dependency version in single place
2.3. Set Java Source 1.8 for using lambda expression

Inside build.gradle set source compatibility and target compatibility java version 1.8 in compile options

3. Add Uses Permission

Add Storage, Camera and Internet permission and uses features in AndroidManifest.xml

4. Create a FileProvider

4.1 In this demo, we get file and Camera/Gallery so we need file provider access for getting file URI. So declare provider in AndroidManifest.xml inside Tag.
4.2 So, define a file provider path. go to res folder and create an XML folder after that create a file with name file_provider_paths.

You must replace com.androidwave.fileupload with your package name

5. Create a Contract for Image for developing MVP design pattern

Go to src folder and create a new source folder name picker for image src ImageContract. Meanwhile, Create a new file inside picker folder with ImageContract.java .

6. Prepare Image Presenter

Go to src=>picker folder and create a new file with ImagePresenter which implementing ImageContract.Presenter class.

So now first part of this project is defined now come to second part which is image uploading

7. Write a Contract for File Uploading

Go to src folder and create a new file with name FileUploaderContract and defined blueprint of Model, View and Presenter.

8. Furthermore, Define File Uploader Model

Simply create a file with FileUploaderModel names and implement FileUploaderContract.Model

9. Create a presenter for File Uploading

Same as previously create a file with FileUploaderPresenter and implement FileUploaderContract.Presenter

Finally, MVP stuff is almost complete

10. Create an API interface for using Retrofit lib

Go in src folder and create an interface with FileUploadService names and create an on file upload method

11. Create Retrofit instance

In src folder create a Retrofit utility class which return Retrofit client using OkHttpClient and RxJava2 CallAdapter

12 . Open build.gradle file define BASE_URL like below

While creating the project, We were selected BasicActivity template. So, MainActivty.java and activity_main.xml was automatically created.

13. Open activity_main.xml and create a profile view using below code

14. Open MainActivity and do following this

In this activity, I dividing into three-part

  1. Bind view with an activity using Butterknife
  2. Getting Image from camera/gallery
  3. Compress the file using FileCompressor utility. (I have explained or the previous article Read Here )
  4. Upload selected to the server

Bind view with activity using Butterknife

Go to setContentView layout xml name do right click and sleeted generate after that generate butter knife injection

Источник

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