How To Post JSON With Retrofit

This tutorial is going to show how to post JSON with Retrofit, a type-safe HTTP client for Android and Java.

1. Library Dependency

We’re going to use Retrofit 2.3.0 for all examples presented in this tutorial. And To use Retrofit with Maven, we will need to include the following dependency into our pom.xml file:

To use Retrofit with Gradle:

2. Rest API

In this tutorial, we will use Retrofit to post Json to a Rest API with the following information:

URL to create a resource (book)

Input

Name Type
name the name of the book
author the author of the book
Response
STATUS 201 if the book is created successfully.

3. Posting JSON With Retrofit

Basically, to post JSON with Retrofit, we will need the following steps:

  • To define a POJO class to represent the JSON that we want to post to the Rest API with Retrofit, or we can simply use a Map with its keys are the field names and values are the field values.
  • When we use the above POJO object as a service method parameter, we annotate it with a @Body annotation to imply that we want to directly control the request body of a POST/PUT request. The object will be serialized using the Retrofit instance Converter and the result will be set directly as the request body.

Next, we will get through the first way to post JSON with Retrofit: to define a POJO class.

3.1. Defining A POJO Class

3.1.1. POJO Class

Let’s define a POJO class called Book to represent the request body:

3.1.2. Defining A Service Interface

Next, we will need to define a service interface which contains all the methods we need to call/invoke from the Rest API:

Notice that we annotated the parameter with @Body annotation.

3.1.3. Posting The POJO Object.

Finally, let’s see how we post the Json with Retfofit:

3.2. Using A Map (HashMap) To Represent The JSON

Instead of defining a POJO class to represent the JSON, we can use a Map to represent the JSON we want to post with Retrofit, then use @Body annotation to instruct Retrofit to serialize the Map into JSON before sending to the Rest API.

3.2.1. Defining A Service Interface

Let’s define another method called updateBook in the above service interface as follows:

Notice that the parameter of the method is an java.util.Map.

3.2.2. Posting The Map

Let’s see how we create the Map and post it in the following example:

After creating the Retrofit and service interface objects, we create a HashMap to represent the Json and then post the map with Retrofit.

4. Conclusions

The tutorial has illustrated how to post JSON with Retrofit by either defining a POJO class or using a Map to represent the JSON, then annotate those with the @Body annotation which instructs Retrofit to serialize those into JSON before making a request to the Rest API. And we can see that defining a POJO class is suitable for all cases that we have fixed JSON schema while the Map is very flexible for the remaining cases.

The source code presented in the tutorial is available on my Github project. And it’s a Maven based project; it’s will be easy to import into IDE such as Eclipse, IntelliJ IDEA, etc.

Below are other related articles for your references:

How to Post with Retrofit 2

Java REST Client Example

Java REST Client Example With Retrofit 2

 

Reactive HTTP Client With Spring 5 WebClient

This article is going to cover about Spring 5 WebClient, a non-blocking, reactive client for HTTP requests with Reactive Streams back pressure.

1. Introduction To Spring 5 WebClient

The WebClient is a non-blocking, reactive HTTP client which has been introduced in Spring 5 and is included in the spring-webflux module. Following are characteristics of the WebClient:

  • Provides a higher level API over HTTP client libraries. By default, it uses Reactor Netty
  • Returns Reactor Flux or Mono for output and accepts Reactive Streams Publisher as input (see Reactive Libraries).
  • Shares HTTP codecs and other infrastructure with the server functional
    web framework.

By comparison to the RestTemplate, the Spring 5 WebClient has some more advantages:

  • It offers a more functional
  • Enables fluent API that taking full advantage of Java 8 lambdas.
  • Supports both sync and async scenarios, including streaming, and brings the efficiency of non-blocking I/O.

2. Spring 5 WebClient API

2.1. Create A WebClient Object

Let’s see how we can create a WebClient object:

We have just configured a base URI for requests performed through the client to avoid repeating the same host, port, base path, or even query parameters with every request.

2.2. Exchange A Request With The exchange() Method

To exchange a request, we can use the exchange() method as the following example:

The method exchanges the request for a ClientResponse with full access to the response status and headers before extracting the body.

2.3. Exchange A Request With The retrieve() Method

Another way to exchange a request with the WebClient is to use the retrieve() method:

The retrieve() method is a variant of the exchange() method that provides the shortest path to retrieving the full response (i.e. status, headers, and body) where instead of returning Mono<ClientResponse> it exposes shortcut methods to extract the response body.

3. Spring 5 WebClient Examples

3.1. Preparation

Assume that we have a REST API to manage Book, produces and consumes JSON data with some basic API(s) as follows:

3.1.1. Read All Books

3.1.2. Read A Specific Book

3.1.3. Create a new book

3.1.4. Update a book

3.1.5. Delete a book

3.1.6. Source Code

The sample source code of the above REST API can be found on my Github project.

3.1.7. The Book POJO

We’re going to define a Book class which represent the response from the above REST API:

3.2. Maven Dependency

We’re going to use Spring Boot 2.0.0.M5 with spring-boot-starter-webflux. Let’s see all Maven dependencies needed in the following part of the pom.xml file:

3.3. Make An HTTP GET Request

In the following example, we’re going to make an HTTP GET request to the REST API to retrieve all the books:

And another example to retrieve a single book:

3.4. Make An HTTP POST Request (Create A Book)

To make an HTTP POST request, at first, we need to call the post() method of the WebClient in order to prepare an HTTP POST request. Then we optionally provide the body for the request and call the retrieve() or exchange() method:

3.4. Make An HTTP PUT Request (Update A Book)

To make an HTTP PUT request, at first, we need to call the put() method of the WebClient in order to prepare an HTTP PUT request. Then we optionally provide the body for the request and call the retrieve() method:

Notice that in above example, firstly we create a Book without the Author in the first request to the server. After that, we update the author for the book in the second request.

3.5. Make An HTTP DELETE Request (delete a book)

To make an HTTP DELETE request, at first, we need to call the delete() method of the WebClient in order to prepare an HTTP DELETE request. Then we optionally supply the data requested by the REST API for the request and call the retrieve() or exchange() method:

In the above example, we create a book first. Then we delete the book and validate the response.

3.6. Make An HTTP Request With Basic Authentication

To make an HTTP request with basic authentication, we can provide the WebClient a filter which adds an Authorization header for HTTP Basic Authentication, based on the given username and password. Notice that Spring 5 already provides us a basic authentication filter which can be found in the ExchangeFilterFunctions class.
Now, let’s see an example of using WebClient to make a request with basic authentication:

4. Conclusion

In this tutorial, we have just got through Spring 5 WebClient, a non-blocking, reactive client for HTTP requests. We’ve learned how to prepare for HTTP GET, POST, PUT, DELETE requests and exchange the request using the exchange() and retrieve() methods. We can see that the easiest way to exchange a request is to use the retrieve() method while we have more control over the response body when we use the exchange() method.

The sample code presented in this tutorial is available on my Github project. It’s a Maven based project, so it’s easy to be imported into IDEs such as IntelliJ, Eclipse, etc.

Below are other related articles:

Java REST Client Examples

Using Netflix Feign with Spring Cloud

Basic Authentication with Open Feign

File Uploading with Open Feign

Java REST Client Using Retrofit 2

Simple Java REST Client Using java.net.URL package

Java REST Client Using Spring RestTemplate

Java REST Client Using Apache HttpClient

Java REST Client Using Jersey Client

Java REST Client Using Resteasy Client

Java REST Client Using Resteasy Client Proxy Framework

Java REST Client Using Apache CXF Proxy-based API

 

 

How to Post with Retrofit 2

This tutorial is going to cover about how to post with Retrofit 2, a type-safe HTTP client for Android and Java applications. We’re going to get though some popular use cases and examples where Retrofit 2 can be used such as how to post a JSON string, how to post an object, how to post a multipart form, encoded form and so on.

1. Preparation

We’re going to use Retrofit 2, version 2.1.0 for all Retrofit 2 post examples in the tutorial. And we also use the Gson library to serialize and deserialize JSON data. Therefore, the Maven dependencies we will be as the following:

The REST API we’re going to use for all Retrofit 2 post examples in this tutorial is httpbin, an free HTTP Request & Response Service for testing.

2. Post An Object

Let’s start to post with Retrofit 2 by an example which we’re going to post an object to the REST API.

Firstly, we need to define an endpoint inside of an interface using Retrofit 2 annotations which will define the HTTP method, request body, parameters and so on.

In the interface, the @POST annotation is used to define the HTTP POST method, and the @Body annotation is used to define a single request body. In addition, the return value is always a parameterized Call<T> object such as Call<Book> and the response will be converted into the T type, Book in this example. If we don’t need any type-specific response, we can specify return value as Call<ResponseBody>.

Next, let’s create the Retrofit 2 instance and test the method:

3. Post A JSON String

Let’s say we have a following JSON string and we want to use Retrofit 2 to post the string to the remote API:

To post a JSON string with Retrofit 2, we can define an POJO that can represent the JSON that we need. For instance, a POJO represents the JSON can be defined in the following way:

Then we can define the endpoint as below:

Because we annotate the parameter with the @Body annotation, Retrofit 2 will use the converter library to serialize the parameter into JSON.

Next, let post the JSON string like we post an object with Retrofit 2:

For more detail about posting JSON, visit another tutorial: How To Post JSON With Retrofit

4. Post A Form Encoded

Form-encoded data is sent when @FormUrlEncoded is present on the method. Each key-value pair is annotated with @Field containing the name and the object providing the value. Let’s see an example which we use Retrofit 2 to post a form encoded to update the resource from remote API.

Endpoint:

The @FormUrlEncoded annotation denotes that the request body will use form URL encoding. Fields should be declared as parameters and annotated with the @Field annotation.

Next, let’s define a test method:

4.1. Post A Form Encoded With @FieldMap

In situations where we just need to send some fields that should be updated for a given resource, we can use the Retrofit 2’s @FieldMap which is a named key/value pairs for a form-encoded request. We can pass a Map which its keys are the field names and paired values are the values we want to update for the resource.

Let’s the following example which we post a form encoded with @FieldMap to update a resource from the API.

The endpoint:

The test method:

5. Post A Multipart Form

We can use Retrofit 2 to post a multipart form in order to upload files or images to remote API. Multipart requests are used when @Multipart is present on the method. Parts are declared using the @Part annotation. Let’s see an example which we post a multipart form to add a cover image for a given Book identified by its id.

Endpoint:

Next, let’s define a test method:

6. Conclusion

The tutorial has just illustrated how to post with Retrofit 2 in different use cases and operations, from how to post an object, how to post a JSON string, how to post a form encoded to how to post a multipart form.

All the Retrofit 2 post examples code in the tutorial is available on my Github project. It’s an Maven based project, so it’s easy to import and run it in any IDE such as Eclipse, Intellij, etc.

Below are other related articles:

Java REST Client Example With Retrofit 2

Java REST Client Example

 

 

 

 

Using Netflix Feign with Spring Cloud

This tutorial is going to cover how to use Netflix Feign with Spring Cloud and how to override default configurations, declare additional configurations for Feign client in Spring Cloud as well.

1. Preparation

1.1. The RESTful Web Service

Let’s assume that our application needs to exchanging data with a RESTful web service which its APIs are described as the following:

1.1.1. Get all books

Responses: application/json

1.1.2. Create a new book

Request

Example:

Responses: application/json

Example:

STATUS 201 if the book is created successfully.

1.1.3. Update a book

1.1.4. Delete a book

1.2. Include Feign into Project

To include Feign into project we can use the starter with group org.springframework.cloud and artifact id spring-cloud-starter-feign. Let’s see a part of the pom.xml as the following:

1.3. Example Source Code

The example source code can be found on the Github project. They are Maven based projects, so it will be easy to import into IDEs such as Eclipse, Intellij, etc.

2. Netflix Feign with Spring Cloud Example

2.1. Activate Feign Client

With Feign added on the classpath, we can activate Feign client by adding the @EnableFeignClients in the main class of the project. Let’s see the following example:

2.2. Create a REST Client Using Feign

We’re going to define an interface which contains all methods map with the remote API using Spring MVC annotations.

The @FeignClient annotation is used to declare that a REST client with that interface should be created. We also named for the client as “book-client”and specify an absolute URL to our above REST API. Note that instead of the url attribute, we can use the name attribute which can be used to create a Ribbon load balancer.

The Ribbon client above will want to discover the physical addresses for the “book-client” service. If our application is a Eureka client then it will resolve the service in the Eureka service registry. If we don’t want to use Eureka, we can simply configure a list of servers in our external configuration.

The Book type which was used above, is a simple POJO as below:

2.3. Test The REST Client

In this part, we’re going to see some JUnit tests to test the above client.

2.3.1. Make a HTTP GET request

2.3.2. Make a HTTP POST request

2.3.3. Make a HTTP PUT request

2.3.4. Make a HTTP DELETE request

3. Advanced Configuration for Netflix Feign with Spring Cloud

3.1. Feign Hystrix Support

If Hystrix is on the classpath, by default Feign will wrap all methods with a circuit breaker. Returning a com.netflix.hystrix.HystrixCommand is also available. This lets us use reactive patterns (with a call to .toObservable() or .observe() or asynchronous use (with a call to .queue()).

3.1.1. Disable Hystrix support for Feign

To disable Hystrix support for Feign, we can set feign.hystrix.enabled=false in the application.properties file.

3.1.2. Enable Fallback Support for Feign Client

Fallbacks are known values, which we can return when there’s an error invoking an HTTP method. For example, we can return a cached result as opposed to raising an error to the caller. To enable fallback support for Feign client, we pass a safe implementation of the target interface as the fallback attribute of the @FeignClient annotation.

Let’s see a safe fallback implementation of the above BookClient.java

Then we set the fallback attribute to the class name that implements the fallback:

3.2. Overriding Feign Default Configurations

Spring Cloud provides a set of default configurations for each Feign client. However, it lets us take full control of the Feign client by overriding default configurations or declaring additional configurations using @FeignClient annotation. For example:

In this case the client is composed from the components already in default configurations together with any in the FeignBookConfiguration.

Spring Cloud Netflix provides the following beans by default for Feign:

Bean Type bean Name Class Name
Decoder feignDecoder ResponseEntityDecoder
Encoder feignEncoder SpringEncoder
Logger feignLogger Slf4jLogger
Contract feignContract SpringMvcContract
Feign.Builder feignBuilder HystrixFeign.Builder
Client feignClient if Ribbon is enabled it is a LoadBalancerFeignClient, otherwise the default feign client is used.

Spring Cloud Netflix does not provide the following beans by default for feign, but still looks up beans of these types from the application context to create the Feign client:

  • Logger.Level
  • Retryer
  • ErrorDecoder
  • Request.Options
  • Collection<RequestInterceptor>

Those beans can be overridden or declared additionally in the configuration file. Followings are some some examples:

3.2.1. Override ConnecTimeout and ReadTimeout for Feign Client

We have set the ConnecTimeout and ReadTimeout to 10 seconds.

3.2.2. Override Feign Logging Level Configuration

By default, no logging is set for Feign client, we have just overridden the the logging level to FULL (Log the headers, body, and metadata for both requests and responses)

3.2.3. Add RequestInterceptor For Feign Client

We have added a Basic Authentication interceptor for the Feign client.

4. Conclusion

The article has just illustrated how to use Netflix Feign with Spring Cloud and how to override default configurations, declare additional configurations for Feign client in Spring Cloud as well. We can see that Spring Cloud facilitates us not only in creating REST clients with Netflix Feign by declaring interfaces using Spring MVC annotations but also in integrating with other libraries such as Ribbon, Eureka, Hystrix and so on. This offers us another good choice beside Spring RestTemplate when our applications need to exchange data with other systems using REST.

5. References

Spring Cloud Netflix documents

Java REST Client Using Netflix Feign

File Uploading with Open Feign

Basic Authentication with Open Feign

 

How to Post with OkHttp

This tutorial is going to cover about how to post with OkHttp, an HTTP & HTTP/2 client for Android and Java applications. We’re going to get though some popular use cases and examples such as how to post a string, how to post a form, how to post a stream and so on.

1. Preparation

We’re going to use OkHttp, version 3.5.0 for all OkHttp post examples in the tutorial, and the only Maven dependency we will need is:

2. Post a String with OkHttp

Let’s see a following example which we will post a string with OkHttp using OkHttpClient.

In the example, after creating the client, we create a request by providing the builder the URL of the remote endpoint, the HTTP Post method and the request body. Note how we created the request body by providing the text we want to post and its media type.

Because the entire request body is in memory simultaneously, we should avoid posting large (greater than 1 MiB) documents using this API.

3. Post a Byte Array

It’s easy to post a byte array with OkHttp. Following is an example that we will post a byte array to a RESTful web service.

4. Post Form Parameters

OkHttp allows us to post form parameters by using FormBody.Builder to build a request body that works like an HTML <form> tag. Names and values will be encoded using an HTML-compatible form URL encoding. Let’s see an example which we will post form parameters with OkHttp using OkHttpClient.

In the example, we have just used the FormBody.builder to create a form with 3 fields: email, firstname, lastname and then posted the form to the remote URL.

5. Post a File

It’s pretty simple to post a file with OkHttp. We can use the RequestBody class to create a request body that transmits the content of a file. Let’s see the following example which we will post a file using OkHttpClient:

In the above example, we have posted the Lorem Ipsum.txt file to a RESTful web service.

6. Post a Stream

With OkHttp, we can POST a request body as a stream. The content of this request body is being generated as it’s being written. Let’s see an example which we will post a stream to a REST API.

In the example, we posted a stream by creating new RequestBody and overriding the writeTo method in which we read the file Lorem Ipsum.txt line by line and streamed into the buffered sink of the request.

7. Post a Multipart Request

We can use the MultipartBody.Builder class to build request bodies compatible with HML file upload forms. We can leverage this feature to upload files, images with OkHttp. Let’s see an example which we will post a multipart request to a RESTful web service.

In the example, we created an instance of the MultipartBody class which is a an RFC 2387-compliant request. Then we added a file part and a description part to the request body, and finally we execute the request to post the form to the RESTful web service.

8. Conclusion

The tutorial has showed us how to post with OkHttp in different ways and use cases from how to post a string, how to post a stream, how to post a Multipart request and so on.

The OkHttp post examples source code can be found on the Github project. It’s an Maven based project, so it’s easy to import and run it in any IDE such as Eclipse, Intellij, etc.

Below are other related tutorials for your references:

How to Cache Response with OkHttp

Java REST Client Examples Using OkHttp

Basic Authentication with OkHttp Example

Upload a File with OkHttp

Set Timeout with OkHttp

Download a File with OkHttp

WebSocket Client Example with OkHttp

 

Set Timeouts with Unirest for Java

1. Introduction

This short tutorial is going to cover how to set timeouts with Unirest for Java, a simplified, lightweight HTTP request library built and maintained by Mashape.

Unirest for Java allows us to set timeouts for its HTTP clients, and this is useful for us to deal with a popular issue of the client-server model is the network partitions issue. And we can use timeouts to fail a call when its peer is unreachable.

Let’s see the signature method in the Unirest class which can be used to set timeouts:

There are 2 timeout parameters we can set are:

  • Connection timeout: The timeout until a connection with the server is established (in milliseconds), and the default value is 10000
  • Socket timeout: The timeout to receive data (in milliseconds), and the default is 60000

We can set any of these timeouts to zero to disable the timeout.

2. Set Timeouts with Unirest for Java example

2.1. Library dependency

The only one dependency for this example is the unirest-java, version 1.4.9

2.2. Example code

Let’s see an example method that set the timeouts with Unirest for Java:

We have just set connection timeout with 60000 milliseconds, socket timeout with 30000 milliseconds.

3. Conclusion

The tutorial has illustrated how to set timeouts with Unirest for Java. This is useful when we want to fail a call if we have an issue with the network.

4. References

Java REST Client Example

Java REST Client Using Unirest Java API

 

File Uploading with Open Feign

This short tutorial is going to cover about file uploading with Open Feign, a java to http client binder.

1. Preparation

1.1. REST API for file uploading

Let’s assume that we have a RESTful web service which provides an API for file uploading as below:

Parameters:

Key Required Description
file required A binary file
name optional The name of the file

1.2. Source code and dependencies

Beside feign-core, we will use feign-form which is module that adds support for encoding application/x-www-form-urlencoded and multipart/form-data forms for Feign requests. Here are the Maven dependencies that will be used for our example:

2. File uploading with Open Feign

2.1. Define a Proxy Interface at the client side

Firstly, we need to define a proxy interface which contains a methods targeted with the REST API for uploading. Let’s see how the interface is defined as below:

We annotate the method by the @RequestLine annotation which specifies the HTTP POST method and the resource path of the API. We also use the @Headers annotation to specify the Content-Type of the request is multipart/form-data.

For more detail about defining proxy interface, you can refer to my recent post about implementing Java REST client using Feign.

2.2. Invoke methods on the Proxy

Now we will define a class which will invoke the method defined proxy interface.

In the above method, we use Feign utility class to create an instance of the above proxy interface (FileUploadResource) with properly encoder (FormEncoder for multi-part file uploading) and the URL of the REST API.

2.3. Verify

Let’s see an example unit test code for the uploadFile method:

3. Conclusion

The tutorial has just illustrated about file uploading with Open Feign. The source code can be found on the Github project or you can download it by clicking on the link java-examples.zip . It is an Maven based project, so it should be easy to import into IDE such as Eclipse, Intellij

4. References

Java REST Client Using Netflix Feign

Basic Authentication with Open Feign

Upload a File with OkHttp

Java REST Client Example

WebSocket Client Example with OkHttp

1. Overview

This tutorial is going to cover how to create a WebSocket client example with OkHttp, an HTTP & HTTP/2 client for Android and Java applications, powered by Square.

2. Preparation

We’re going to use OkHttp3, version 3.5.0 for the example.

3. WebSocket Client Example with OkHttp

In this section, we’re going to create a WebSocket client which will connect to the websocket.org, an online service to test WebSocket-based applications and services.

Firstly, let’s see the newWebSocket method which is offered by the OkHttpClient class , use request to connect a new web socket:

Because the method requires an instance of the Request class and an instance of the WebSocketListener class as parameters in order to create a WebSocket, we’re going to create those objects step by step.

3.1. Create an  instance of the WebSocketListener

Because the WebSocketListener is an abstract class, we should extend it first before we can create an instance of it. Let’s see an example how we extend it by our EchoWebSocketListener class:

Here are a few notes for the above methods:

  • The onOpen method is invoked when a web socket has been accepted by the remote peer and may begin transmitting messages. In this example, we will send 3 messages to the remote WebSocket service and then close our client.
  • The onMessage methods are invoked when a message has been received. The first method is used for text messages while the second is used for binary messages.
  • The onClosing method is invoked when the peer has indicated that no more incoming messages will be transmitted. Notice that we have passed the status code 1000 to imply that the closing is normal closure. You can find more status codes on Section 7.4 of RFC 6455.
  • The onFailure method is invoked when a web socket has been closed due to an error reading from or writing to the network.

3.2. Create an instance of the Request class

Create an instance of the Request class is pretty simple. Let’s see an example as below:

We have just created an request the WebSocket service we’re going to test in tutorial.

3.3. Put it all together

Let’s create a class with a main method to test our source code:

Running the example will print out the following messages into the console:

4. Conclusion

The tutorial has shown you how to create a WebSocket client example with OkHttp. This feature is useful for us to create application that support fully bi-directional streaming of messages between client and server.

The example source code can be found on the Github project or you can download it by clicking on java-examples.zip. It is an Maven-based project, so it will be easy for you to import it into IDEs such as Eclipse, Intellij, etc.

5. Reference

OkHttp on Github

Java REST Client Examples Using OkHttp

Basic Authentication with OkHttp Example

Upload a File with OkHttp

Set Timeout with OkHttp

Download a File with OkHttp

How to Cache Response with OkHttp

 

 

Basic Authentication with Open Feign

This tutorial is going to illustrate how to do basic authentication with Open Feign, a java to http client binder powered by OpenFiegn.

1. Overview

In general, we will use the BasicAuthRequestInterceptor class, which is an interceptor that adds the request header needed to use HTTP basic authentication, for basic authentication purposes.

In this tutorial, let’s assume that we will consume a REST API that requires basic authentication on the https://httpbin.org/, a HTTP Client Testing Service. The REST API which returns the current authenticated user and status, can be described as below:

Responses: application/json

Example:

STATUS 200 if get resource successfully.
STATUS 401 if not authorized.

2. The source code

In this tutorial, we will use the Feign version: 8.18.0. The Maven dependencies are as below:

The source code can be found on Github or you can download it via the link:java-examples.zip

3. Basic Authentication with Open Feign

3.1. Define a Proxy Interface at the client side

Firstly, we need to define a proxy interface which contains all methods targeted with the REST API. Let’s see how the interface is defined as below:

For more detail, you can refer to my recent post about implementing Java REST client using Feign.

As for the response, we also need to define a class to bind with it. Let’s see how it is defined:

3.2. Invoke methods on the Proxy

Now we will invoke the method defined on the Proxy Interface. Note that the method require basic authentication. Let’s see an example code:

Here are some essential points:

  • We create a instance of the BasicAuthRequestInterceptor with default username and password for basic authentication with the REST API and set it as a request interceptor of the Feign targeted http apis.
  • We use JacksonEncoder to convert the response into our AuthStatus object.

3.3. Verify

Let’s write a piece of unit test for the method:

Running the test will give the Green color.

4. Conclusion

The tutorial has just shown you how to do basic authentication with Open Feign by using the BasicAuthRequestInterceptor class as a request interceptor. Beside, there are other approaches to do basic authentication and we will get to know in next posts. Here are other related articles:

Java REST Client Using Netflix Feign

File Uploading with Open Feign

Java REST Client Example

 

 

 

Upload a File with OkHttp

This tutorial will cover how to upload a file with OkHttp, an HTTP & HTTP/2 client for Android and Java applications, powered by Square.

1. Preparation

1.1. REST API for file uploading

Let’s assume that we have a RESTful web service which provides an API for file uploading as below:

Parameters:

Key Required Description
file required A binary file
name optional The name of the file

1.2. The client side source code

The demo source code can be found on the Github or you can download it here: Java-Examples.zip

We will use the OkHttp 3.4.1 to upload files to the REST API, and the dependency we need is:

2. Upload a File with OkHttp

In this section, we will illustrate how to make a multipart upload request using OkHttp client library.A multipart upload request allows us to send metadata along with the data to upload.

Let’s see an example code how to upload image to the above REST API:

There are a few of notices from the source code:

  • Firstly we create an instance of the MultipartBody, an RFC 2387-compliant request body, as the body of the request we will issue to the REST API.
  • Then we use the addFormDataPart method to add a form data part. The parameters for the method includes the part name, the file name and the binary file.
  • Finally, we create the request with the REST URI, the body we have just created and invoke the request.

3. Server side source code

This section describes an example of server side source code implemented for the REST API. The source code is implemented using Spring Boot and can be found on my Github project.

The upload method has only one parameter: file and the type is MulipartFile.

4. Conclusion

The tutorial has just presented how to upload a file with OkHttp. We have just performed a multipart upload to the REST API. And we also have seen an example how the server side is implemented. Note that beside the multipart upload, we can use another way to upload a file to a REST API by using Chunked transfer encoding. We will get to know it in another article. Below are other related articles for your references:

OkHttp Post Examples

Java REST Client Examples Using OkHttp

Basic Authentication with OkHttp Example

Download a File with OkHttp

Set Timeout with OkHttp

WebSocket Client Example with OkHttp