SlideShare a Scribd company logo
5
FEATURES OF UNIREST
• Make GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS requests
• Both syncronous and asynchronous (non-blocking) requests
• It supports form parameters, file uploads and custom body entities
• Easily add route parameters without ugly string concatenations
• Supports gzip
• Supports Basic Authentication natively
• Customizable timeout, concurrency levels and proxy settings
• Customizable default headers for every request (DRY)
• Customizable HttpClient and HttpAsyncClient implementation
• Automatic JSON parsing into a native object for JSON responses
• Customizable binding, with mapping from response body to java Object
Most read
8
MAKE GET, POST, PUT, PATCH,
DELETE, HEAD, OPTIONS REQUESTS
➤ GET:
final HttpResponse<String> response = Unirest.get("http://httpbin.org/get").asString();
System.out.println( response.getBody() );
➤ POST:
HttpResponse<String> jsonResponse = Unirest.post("http://httpbin.org/post")
.header("accept", "application/json")
.queryString("apiKey", "123")
.field("parameter", "value")
.field("foo", "bar")
.asString();
System.out.println( response.getBody() );
➤ PUT:
final HttpResponse<String> response = Unirest.put(“http://httpbin.org/put").asString();
System.out.println( response.getBody() );
➤ DELETE:
final HttpResponse<String> response = Unirest.delete("http://httpbin.org/delete").asString();
System.out.println( response.getBody() );
➤ HEAD:
final HttpResponse<String> response = Unirest.head("http://httpbin.org/head").asString();
System.out.println( response.getBody() );
Most read
20
CUSTOMIZABLE BINDING, WITH MAPPING FROM
RESPONSE BODY TO JAVA OBJECT
Before an asObject(Class) or a .body(Object) invokation, is necessary to provide a custom implementation of
the ObjectMapper interface. This should be done only the first time, as the instance of the ObjectMapper will be shared
globally.
For example, serializing Json fromto Object using the popular Jackson ObjectMapper takes only few lines of code.
.
// Only one time
Unirest.setObjectMapper(new ObjectMapper() {
private com.fasterxml.jackson.databind.ObjectMapper jacksonObjectMapper
= new com.fasterxml.jackson.databind.ObjectMapper();
public <T> T readValue(String value, Class<T> valueType) {
try {
return jacksonObjectMapper.readValue(value, valueType);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Most read
UNIREST: AGENDA
1. Introduction to Unirest: (Link: https://interviewbubble.com/unirest-java-tutorial/)
➤ Why Unirest needed?
➤ What is UniRest?
➤ Features of Unirest
➤ Availability and support for Unirest
2. Installation and Setup
3. Features Details and how to use:
➤ Make GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS requests
➤ Both syncronous and asynchronous (non-blocking) requests
➤ Supports form parameters, file uploads and custom body entities
➤ Easily add route parameters without ugly string concatenations
➤ Supports gzip
➤ Supports Basic Authentication natively
➤ Customizable timeout, concurrency levels and proxy settings
➤ Customizable default headers for every request (DRY)
➤ Customizable HttpClient and HttpAsyncClient implementation
➤ Automatic JSON parsing into a native object for JSON responses
➤ Customizable binding, with mapping from response body to java Object
4. Demo Project: Java REST Client Using Unirest Java API
https://interviewbubble.com/unirest-java-tutorial/
INTRODUCTION TO UNIREST: WHY
UNIREST NEEDED?
private static void sendGET() throws IOException {
URL obj = new URL(GET_URL);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("GET Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
} else {
System.out.println("GET request not worked”);
}
EQUIVALENT UNIREST CODE
final HttpResponse<String> response = Unirest.get("http://httpbin.org/get").asString();
Advantages:
1. Less code: good for rapid software development
2. Easy to use: easy to debug
3. Support Available in multiple languages
4. Method level access available
5. Automatic JSON parsing into a native object for JSON responses
6. Customizable binding, with mapping from response body to java Object
WHAT IS UNIREST?
Unirest is lightweight HTTP request client libraries available in multiple
languages including Java, .NET, Ruby, Node, Objective-C, etc.
Goal:
Unirest aims to simplify making HTTP REST requests.
Backend: Apache Http-client
It is Same as JDBI on top of JDBC
FEATURES OF UNIREST
• Make GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS requests
• Both syncronous and asynchronous (non-blocking) requests
• It supports form parameters, file uploads and custom body entities
• Easily add route parameters without ugly string concatenations
• Supports gzip
• Supports Basic Authentication natively
• Customizable timeout, concurrency levels and proxy settings
• Customizable default headers for every request (DRY)
• Customizable HttpClient and HttpAsyncClient implementation
• Automatic JSON parsing into a native object for JSON responses
• Customizable binding, with mapping from response body to java Object
AVAILABILITY AND SUPPORT FOR
UNIREST
.
Installation and Setup
With Maven
You can use Maven by including the library:
There are dependencies for Unirest-Java, these should be already installed, and they are as follows:
1. httpclient
2. httpasyncclient
.
MAKE GET, POST, PUT, PATCH,
DELETE, HEAD, OPTIONS REQUESTS
➤ GET:
final HttpResponse<String> response = Unirest.get("http://httpbin.org/get").asString();
System.out.println( response.getBody() );
➤ POST:
HttpResponse<String> jsonResponse = Unirest.post("http://httpbin.org/post")
.header("accept", "application/json")
.queryString("apiKey", "123")
.field("parameter", "value")
.field("foo", "bar")
.asString();
System.out.println( response.getBody() );
➤ PUT:
final HttpResponse<String> response = Unirest.put(“http://httpbin.org/put").asString();
System.out.println( response.getBody() );
➤ DELETE:
final HttpResponse<String> response = Unirest.delete("http://httpbin.org/delete").asString();
System.out.println( response.getBody() );
➤ HEAD:
final HttpResponse<String> response = Unirest.head("http://httpbin.org/head").asString();
System.out.println( response.getBody() );
SYNCRONOUS & ASYNCHRONOUS
(NON-BLOCKING) REQUESTS
Type to enter a caption.
SYNCRONOUS & ASYNCHRONOUS
(NON-BLOCKING) REQUESTS
Sometimes, well most of the time, you want your application to be asynchronous and not block, Unirest supports this in Java
using anonymous callbacks, or direct method placement:
using java.util.concurrent.Future and callback methods:
Future<HttpResponse<JsonNode>> future = Unirest.post("http://httpbin.org/post")
.header("accept", "application/json")
.field("param1", "value1")
.field("param2", "value2")
.asJsonAsync(new Callback<JsonNode>() {
public void failed(UnirestException e) {
System.out.println("The request has failed");
}
public void completed(HttpResponse<JsonNode> response) {
int code = response.getStatus();
Map<String, String> headers = response.getHeaders();
JsonNode body = response.getBody();
InputStream rawBody = response.getRawBody();
}
FORM PARAMETERS, FILE UPLOADS
AND CUSTOM BODY ENTITIES
➤ Form Params
➤ File Upload:
➤ Custom body
.
.
.
ROUTE PARAMETERS
Sometimes you want to add dynamic parameters in the URL, you can easily do that by
adding a placeholder in the URL, and then by setting the route parameters with
the routeParam function, like:
Type to enter a caption.
SUPPORTS GZIP
➤ Using setDefaultHeader method we can use GZIP.
Unirest.setDefaultHeader(“Accept-Encoding", "gzip");
BASIC AUTHENTICATION
Authenticating the request with basic authentication can be done by
calling the basicAuth(username, password) function:
.
CUSTOMIZABLE TIMEOUT, LEVELS
AND PROXY SETTINGS
1. Customizable timeout
You can set custom connection and socket timeout values (in milliseconds):
By default the connection timeout (the time it takes to connect to a server) is 10000, and the socket timeout (the time it takes to
receive data) is 60000. You can set any of these timeouts to zero to disable the timeout.
Configure connection and socket timeouts :
1
Unirest.setTimeouts(20000, 15000)
2. Customizable levels: Let’s set the number of connections and number maximum
connections per route:
.
CUSTOMIZABLE TIMEOUT, LEVELS
AND PROXY SETTINGS
Proxy settings:
You can set a proxy by invoking:
.
CUSTOMIZABLE DEFAULT HEADERS
Default Request Headers
You can set default headers that will be sent on every request:
Unirest.setDefaultHeader("Accept-Language", "en-GB,en-US;q=0.9,en;q=0.81");
Clear Default Header:
You can clear the default headers anytime with:
Unirest.clearDefaultHeaders();
.
Customizable HttpClient and HttpAsyncClient implementation
You can explicitly set your
own HttpClient and HttpAsyncClient implementations by using
the following methods:
Unirest.setHttpClient(httpClient);
Unirest.setAsyncHttpClient(asyncHttpClient);
AUTOMATIC JSON PARSING INTO A NATIVE
OBJECT FOR JSON RESPONSES
➤ Unirest uses Jackson lib to parse JSON responses into java
object.
HttpResponse<JsonNode> jsonResponse = Unirest.post("http://httpbin.org/post")
.header("accept", "application/json")
.field("parameter", "value")
.field("file", new File("/tmp/file"))
.asJson();
.
CUSTOMIZABLE BINDING, WITH MAPPING FROM
RESPONSE BODY TO JAVA OBJECT
Before an asObject(Class) or a .body(Object) invokation, is necessary to provide a custom implementation of
the ObjectMapper interface. This should be done only the first time, as the instance of the ObjectMapper will be shared
globally.
For example, serializing Json fromto Object using the popular Jackson ObjectMapper takes only few lines of code.
.
// Only one time
Unirest.setObjectMapper(new ObjectMapper() {
private com.fasterxml.jackson.databind.ObjectMapper jacksonObjectMapper
= new com.fasterxml.jackson.databind.ObjectMapper();
public <T> T readValue(String value, Class<T> valueType) {
try {
return jacksonObjectMapper.readValue(value, valueType);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
CUSTOMIZABLE BINDING, WITH MAPPING FROM
RESPONSE BODY TO JAVA OBJECT
// Response to Object
HttpResponse<Book> bookResponse = Unirest.get("http://httpbin.org/books/1").asObject(Book.class);
Book bookObject = bookResponse.getBody();
HttpResponse<Author> authorResponse = Unirest.get("http://httpbin.org/books/{id}/author")
.routeParam("id", bookObject.getId())
.asObject(Author.class);
Author authorObject = authorResponse.getBody();
// Object to Json
HttpResponse<JsonNode> postResponse = Unirest.post("http://httpbin.org/authors/post")
.header("accept", "application/json")
.header("Content-Type", "application/json")
.
Demo Project: Java REST Client Using Unirest Java API
➤ Check this link: https://interviewbubble.com/demo-project-java-
rest-client-using-unirest-java-api/
THANK YOU
Unirest.shutdown();

More Related Content

What's hot (20)

思ったほど怖くない! Haskell on JVM 超入門 #jjug_ccc #ccc_l8
思ったほど怖くない! Haskell on JVM 超入門 #jjug_ccc #ccc_l8思ったほど怖くない! Haskell on JVM 超入門 #jjug_ccc #ccc_l8
思ったほど怖くない! Haskell on JVM 超入門 #jjug_ccc #ccc_l8
y_taka_23
 
[기초] GIT 교육 자료
[기초] GIT 교육 자료[기초] GIT 교육 자료
[기초] GIT 교육 자료
JUNPIL PARK
 
JSON-LD: JSON for Linked Data
JSON-LD: JSON for Linked DataJSON-LD: JSON for Linked Data
JSON-LD: JSON for Linked Data
Gregg Kellogg
 
Elasticsearch Introduction
Elasticsearch IntroductionElasticsearch Introduction
Elasticsearch Introduction
Roopendra Vishwakarma
 
Cookie & Session In ASP.NET
Cookie & Session In ASP.NETCookie & Session In ASP.NET
Cookie & Session In ASP.NET
ShingalaKrupa
 
The Art of Metaprogramming in Java
The Art of Metaprogramming in Java  The Art of Metaprogramming in Java
The Art of Metaprogramming in Java
Abdelmonaim Remani
 
elasticsearch_적용 및 활용_정리
elasticsearch_적용 및 활용_정리elasticsearch_적용 및 활용_정리
elasticsearch_적용 및 활용_정리
Junyi Song
 
Presentation of bootstrap
Presentation of bootstrapPresentation of bootstrap
Presentation of bootstrap
1amitgupta
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
Joshua Long
 
Composer 套件管理
Composer 套件管理Composer 套件管理
Composer 套件管理
Shengyou Fan
 
모바일 메신저 아키텍쳐 소개
모바일 메신저 아키텍쳐 소개모바일 메신저 아키텍쳐 소개
모바일 메신저 아키텍쳐 소개
Hyogi Jung
 
What is a Full stack developer? - Tech talk
What is a Full stack developer? - Tech talk What is a Full stack developer? - Tech talk
What is a Full stack developer? - Tech talk
Bui Hai An
 
JavaScript - Chapter 7 - Advanced Functions
 JavaScript - Chapter 7 - Advanced Functions JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced Functions
WebStackAcademy
 
react-scriptsはwebpackで何をしているのか
react-scriptsはwebpackで何をしているのかreact-scriptsはwebpackで何をしているのか
react-scriptsはwebpackで何をしているのか
暁 三宅
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPs
Ravi Bhadauria
 
Recursive Query Throwdown
Recursive Query ThrowdownRecursive Query Throwdown
Recursive Query Throwdown
Karwin Software Solutions LLC
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
Abul Hasan
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
ecosio GmbH
 
JQuery introduction
JQuery introductionJQuery introduction
JQuery introduction
NexThoughts Technologies
 
ADO.NET Entity Framework
ADO.NET Entity FrameworkADO.NET Entity Framework
ADO.NET Entity Framework
Doncho Minkov
 
思ったほど怖くない! Haskell on JVM 超入門 #jjug_ccc #ccc_l8
思ったほど怖くない! Haskell on JVM 超入門 #jjug_ccc #ccc_l8思ったほど怖くない! Haskell on JVM 超入門 #jjug_ccc #ccc_l8
思ったほど怖くない! Haskell on JVM 超入門 #jjug_ccc #ccc_l8
y_taka_23
 
[기초] GIT 교육 자료
[기초] GIT 교육 자료[기초] GIT 교육 자료
[기초] GIT 교육 자료
JUNPIL PARK
 
JSON-LD: JSON for Linked Data
JSON-LD: JSON for Linked DataJSON-LD: JSON for Linked Data
JSON-LD: JSON for Linked Data
Gregg Kellogg
 
Cookie & Session In ASP.NET
Cookie & Session In ASP.NETCookie & Session In ASP.NET
Cookie & Session In ASP.NET
ShingalaKrupa
 
The Art of Metaprogramming in Java
The Art of Metaprogramming in Java  The Art of Metaprogramming in Java
The Art of Metaprogramming in Java
Abdelmonaim Remani
 
elasticsearch_적용 및 활용_정리
elasticsearch_적용 및 활용_정리elasticsearch_적용 및 활용_정리
elasticsearch_적용 및 활용_정리
Junyi Song
 
Presentation of bootstrap
Presentation of bootstrapPresentation of bootstrap
Presentation of bootstrap
1amitgupta
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
Joshua Long
 
Composer 套件管理
Composer 套件管理Composer 套件管理
Composer 套件管理
Shengyou Fan
 
모바일 메신저 아키텍쳐 소개
모바일 메신저 아키텍쳐 소개모바일 메신저 아키텍쳐 소개
모바일 메신저 아키텍쳐 소개
Hyogi Jung
 
What is a Full stack developer? - Tech talk
What is a Full stack developer? - Tech talk What is a Full stack developer? - Tech talk
What is a Full stack developer? - Tech talk
Bui Hai An
 
JavaScript - Chapter 7 - Advanced Functions
 JavaScript - Chapter 7 - Advanced Functions JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced Functions
WebStackAcademy
 
react-scriptsはwebpackで何をしているのか
react-scriptsはwebpackで何をしているのかreact-scriptsはwebpackで何をしているのか
react-scriptsはwebpackで何をしているのか
暁 三宅
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPs
Ravi Bhadauria
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
Abul Hasan
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
ecosio GmbH
 
ADO.NET Entity Framework
ADO.NET Entity FrameworkADO.NET Entity Framework
ADO.NET Entity Framework
Doncho Minkov
 

Similar to Unirest Java Tutorial | Java Http Client (20)

Elasticsearch und die Java-Welt
Elasticsearch und die Java-WeltElasticsearch und die Java-Welt
Elasticsearch und die Java-Welt
Florian Hopf
 
Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java
Baruch Sadogursky
 
Android and REST
Android and RESTAndroid and REST
Android and REST
Roman Woźniak
 
nodejs_at_a_glance, understanding java script
nodejs_at_a_glance, understanding java scriptnodejs_at_a_glance, understanding java script
nodejs_at_a_glance, understanding java script
mohammedarshadhussai4
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
WalaSidhom1
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with Express
Aaron Stannard
 
RESTing with JAX-RS
RESTing with JAX-RSRESTing with JAX-RS
RESTing with JAX-RS
Ezewuzie Emmanuel Okafor
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
Oleg Podsechin
 
Simple REST with Dropwizard
Simple REST with DropwizardSimple REST with Dropwizard
Simple REST with Dropwizard
Andrei Savu
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
orkaplan
 
Exploring Node.jS
Exploring Node.jSExploring Node.jS
Exploring Node.jS
Deepu S Nath
 
Andrei shakirin rest_cxf
Andrei shakirin rest_cxfAndrei shakirin rest_cxf
Andrei shakirin rest_cxf
Aravindharamanan S
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
Amit Thakkar
 
JUDCON India 2014 Java EE 7 talk
JUDCON India 2014 Java EE 7 talkJUDCON India 2014 Java EE 7 talk
JUDCON India 2014 Java EE 7 talk
Vijay Nair
 
Node.js 1, 2, 3
Node.js 1, 2, 3Node.js 1, 2, 3
Node.js 1, 2, 3
Jian-Hong Pan
 
JCache Using JCache
JCache Using JCacheJCache Using JCache
JCache Using JCache
日本Javaユーザーグループ
 
RESTful web service with JBoss Fuse
RESTful web service with JBoss FuseRESTful web service with JBoss Fuse
RESTful web service with JBoss Fuse
ejlp12
 
Groovy & Grails eXchange 2012 vert.x presentation
Groovy & Grails eXchange 2012 vert.x presentationGroovy & Grails eXchange 2012 vert.x presentation
Groovy & Grails eXchange 2012 vert.x presentation
Stuart (Pid) Williams
 
Automated testing web services - part 1
Automated testing web services - part 1Automated testing web services - part 1
Automated testing web services - part 1
Aleh Struneuski
 
Angular 4 The new Http Client Module
Angular 4 The new Http Client ModuleAngular 4 The new Http Client Module
Angular 4 The new Http Client Module
arjun singh
 
Elasticsearch und die Java-Welt
Elasticsearch und die Java-WeltElasticsearch und die Java-Welt
Elasticsearch und die Java-Welt
Florian Hopf
 
Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java
Baruch Sadogursky
 
nodejs_at_a_glance, understanding java script
nodejs_at_a_glance, understanding java scriptnodejs_at_a_glance, understanding java script
nodejs_at_a_glance, understanding java script
mohammedarshadhussai4
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
WalaSidhom1
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with Express
Aaron Stannard
 
Simple REST with Dropwizard
Simple REST with DropwizardSimple REST with Dropwizard
Simple REST with Dropwizard
Andrei Savu
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
orkaplan
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
Amit Thakkar
 
JUDCON India 2014 Java EE 7 talk
JUDCON India 2014 Java EE 7 talkJUDCON India 2014 Java EE 7 talk
JUDCON India 2014 Java EE 7 talk
Vijay Nair
 
RESTful web service with JBoss Fuse
RESTful web service with JBoss FuseRESTful web service with JBoss Fuse
RESTful web service with JBoss Fuse
ejlp12
 
Groovy & Grails eXchange 2012 vert.x presentation
Groovy & Grails eXchange 2012 vert.x presentationGroovy & Grails eXchange 2012 vert.x presentation
Groovy & Grails eXchange 2012 vert.x presentation
Stuart (Pid) Williams
 
Automated testing web services - part 1
Automated testing web services - part 1Automated testing web services - part 1
Automated testing web services - part 1
Aleh Struneuski
 
Angular 4 The new Http Client Module
Angular 4 The new Http Client ModuleAngular 4 The new Http Client Module
Angular 4 The new Http Client Module
arjun singh
 
Ad

Recently uploaded (20)

362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
djiceramil
 
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghjfHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
yadavshivank2006
 
11th International Conference on Data Mining (DaMi 2025)
11th International Conference on Data Mining (DaMi 2025)11th International Conference on Data Mining (DaMi 2025)
11th International Conference on Data Mining (DaMi 2025)
kjim477n
 
Semi-Conductor ppt ShubhamSeSemi-Con.pptx
Semi-Conductor ppt ShubhamSeSemi-Con.pptxSemi-Conductor ppt ShubhamSeSemi-Con.pptx
Semi-Conductor ppt ShubhamSeSemi-Con.pptx
studyshubham18
 
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journeyRigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Yannis
 
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) ProjectMontreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Alexandra N. Martinez
 
Présentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptxPrésentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptx
KHADIJAESSAKET
 
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptxDevelopment of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
aniket862935
 
Airport_Substation_With_Diagrams (2).pptx
Airport_Substation_With_Diagrams (2).pptxAirport_Substation_With_Diagrams (2).pptx
Airport_Substation_With_Diagrams (2).pptx
BibekMedhi2
 
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODSWIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
samueljackson3773
 
Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)
pelumiadigun2006
 
First Review PPT gfinal gyft ftu liu yrfut go
First Review PPT gfinal gyft  ftu liu yrfut goFirst Review PPT gfinal gyft  ftu liu yrfut go
First Review PPT gfinal gyft ftu liu yrfut go
Sowndarya6
 
社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought                           .社内勉強会資料_Chain of Thought                           .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptxWeek 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
dayananda54
 
Artificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowyArtificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowy
dominikamizerska1
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
chemistry investigatory project for class 12
chemistry investigatory project for class 12chemistry investigatory project for class 12
chemistry investigatory project for class 12
Susis10
 
ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025
Rahul
 
Structure of OS ppt Structure of OsS ppt
Structure of OS ppt Structure of OsS pptStructure of OS ppt Structure of OsS ppt
Structure of OS ppt Structure of OsS ppt
Wahajch
 
Computer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdfComputer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdf
kumarprem6767merp
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
djiceramil
 
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghjfHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
yadavshivank2006
 
11th International Conference on Data Mining (DaMi 2025)
11th International Conference on Data Mining (DaMi 2025)11th International Conference on Data Mining (DaMi 2025)
11th International Conference on Data Mining (DaMi 2025)
kjim477n
 
Semi-Conductor ppt ShubhamSeSemi-Con.pptx
Semi-Conductor ppt ShubhamSeSemi-Con.pptxSemi-Conductor ppt ShubhamSeSemi-Con.pptx
Semi-Conductor ppt ShubhamSeSemi-Con.pptx
studyshubham18
 
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journeyRigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Yannis
 
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) ProjectMontreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Alexandra N. Martinez
 
Présentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptxPrésentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptx
KHADIJAESSAKET
 
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptxDevelopment of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
aniket862935
 
Airport_Substation_With_Diagrams (2).pptx
Airport_Substation_With_Diagrams (2).pptxAirport_Substation_With_Diagrams (2).pptx
Airport_Substation_With_Diagrams (2).pptx
BibekMedhi2
 
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODSWIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
samueljackson3773
 
Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)
pelumiadigun2006
 
First Review PPT gfinal gyft ftu liu yrfut go
First Review PPT gfinal gyft  ftu liu yrfut goFirst Review PPT gfinal gyft  ftu liu yrfut go
First Review PPT gfinal gyft ftu liu yrfut go
Sowndarya6
 
社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought                           .社内勉強会資料_Chain of Thought                           .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptxWeek 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
dayananda54
 
Artificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowyArtificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowy
dominikamizerska1
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
chemistry investigatory project for class 12
chemistry investigatory project for class 12chemistry investigatory project for class 12
chemistry investigatory project for class 12
Susis10
 
ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025
Rahul
 
Structure of OS ppt Structure of OsS ppt
Structure of OS ppt Structure of OsS pptStructure of OS ppt Structure of OsS ppt
Structure of OS ppt Structure of OsS ppt
Wahajch
 
Computer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdfComputer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdf
kumarprem6767merp
 
Ad

Unirest Java Tutorial | Java Http Client

  • 1. UNIREST: AGENDA 1. Introduction to Unirest: (Link: https://interviewbubble.com/unirest-java-tutorial/) ➤ Why Unirest needed? ➤ What is UniRest? ➤ Features of Unirest ➤ Availability and support for Unirest 2. Installation and Setup 3. Features Details and how to use: ➤ Make GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS requests ➤ Both syncronous and asynchronous (non-blocking) requests ➤ Supports form parameters, file uploads and custom body entities ➤ Easily add route parameters without ugly string concatenations ➤ Supports gzip ➤ Supports Basic Authentication natively ➤ Customizable timeout, concurrency levels and proxy settings ➤ Customizable default headers for every request (DRY) ➤ Customizable HttpClient and HttpAsyncClient implementation ➤ Automatic JSON parsing into a native object for JSON responses ➤ Customizable binding, with mapping from response body to java Object 4. Demo Project: Java REST Client Using Unirest Java API https://interviewbubble.com/unirest-java-tutorial/
  • 2. INTRODUCTION TO UNIREST: WHY UNIREST NEEDED? private static void sendGET() throws IOException { URL obj = new URL(GET_URL); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("User-Agent", USER_AGENT); int responseCode = con.getResponseCode(); System.out.println("GET Response Code :: " + responseCode); if (responseCode == HttpURLConnection.HTTP_OK) { // success BufferedReader in = new BufferedReader(new InputStreamReader( con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // print result System.out.println(response.toString()); } else { System.out.println("GET request not worked”); }
  • 3. EQUIVALENT UNIREST CODE final HttpResponse<String> response = Unirest.get("http://httpbin.org/get").asString(); Advantages: 1. Less code: good for rapid software development 2. Easy to use: easy to debug 3. Support Available in multiple languages 4. Method level access available 5. Automatic JSON parsing into a native object for JSON responses 6. Customizable binding, with mapping from response body to java Object
  • 4. WHAT IS UNIREST? Unirest is lightweight HTTP request client libraries available in multiple languages including Java, .NET, Ruby, Node, Objective-C, etc. Goal: Unirest aims to simplify making HTTP REST requests. Backend: Apache Http-client It is Same as JDBI on top of JDBC
  • 5. FEATURES OF UNIREST • Make GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS requests • Both syncronous and asynchronous (non-blocking) requests • It supports form parameters, file uploads and custom body entities • Easily add route parameters without ugly string concatenations • Supports gzip • Supports Basic Authentication natively • Customizable timeout, concurrency levels and proxy settings • Customizable default headers for every request (DRY) • Customizable HttpClient and HttpAsyncClient implementation • Automatic JSON parsing into a native object for JSON responses • Customizable binding, with mapping from response body to java Object
  • 6. AVAILABILITY AND SUPPORT FOR UNIREST .
  • 7. Installation and Setup With Maven You can use Maven by including the library: There are dependencies for Unirest-Java, these should be already installed, and they are as follows: 1. httpclient 2. httpasyncclient .
  • 8. MAKE GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS REQUESTS ➤ GET: final HttpResponse<String> response = Unirest.get("http://httpbin.org/get").asString(); System.out.println( response.getBody() ); ➤ POST: HttpResponse<String> jsonResponse = Unirest.post("http://httpbin.org/post") .header("accept", "application/json") .queryString("apiKey", "123") .field("parameter", "value") .field("foo", "bar") .asString(); System.out.println( response.getBody() ); ➤ PUT: final HttpResponse<String> response = Unirest.put(“http://httpbin.org/put").asString(); System.out.println( response.getBody() ); ➤ DELETE: final HttpResponse<String> response = Unirest.delete("http://httpbin.org/delete").asString(); System.out.println( response.getBody() ); ➤ HEAD: final HttpResponse<String> response = Unirest.head("http://httpbin.org/head").asString(); System.out.println( response.getBody() );
  • 9. SYNCRONOUS & ASYNCHRONOUS (NON-BLOCKING) REQUESTS Type to enter a caption.
  • 10. SYNCRONOUS & ASYNCHRONOUS (NON-BLOCKING) REQUESTS Sometimes, well most of the time, you want your application to be asynchronous and not block, Unirest supports this in Java using anonymous callbacks, or direct method placement: using java.util.concurrent.Future and callback methods: Future<HttpResponse<JsonNode>> future = Unirest.post("http://httpbin.org/post") .header("accept", "application/json") .field("param1", "value1") .field("param2", "value2") .asJsonAsync(new Callback<JsonNode>() { public void failed(UnirestException e) { System.out.println("The request has failed"); } public void completed(HttpResponse<JsonNode> response) { int code = response.getStatus(); Map<String, String> headers = response.getHeaders(); JsonNode body = response.getBody(); InputStream rawBody = response.getRawBody(); }
  • 11. FORM PARAMETERS, FILE UPLOADS AND CUSTOM BODY ENTITIES ➤ Form Params ➤ File Upload: ➤ Custom body . . .
  • 12. ROUTE PARAMETERS Sometimes you want to add dynamic parameters in the URL, you can easily do that by adding a placeholder in the URL, and then by setting the route parameters with the routeParam function, like: Type to enter a caption.
  • 13. SUPPORTS GZIP ➤ Using setDefaultHeader method we can use GZIP. Unirest.setDefaultHeader(“Accept-Encoding", "gzip");
  • 14. BASIC AUTHENTICATION Authenticating the request with basic authentication can be done by calling the basicAuth(username, password) function: .
  • 15. CUSTOMIZABLE TIMEOUT, LEVELS AND PROXY SETTINGS 1. Customizable timeout You can set custom connection and socket timeout values (in milliseconds): By default the connection timeout (the time it takes to connect to a server) is 10000, and the socket timeout (the time it takes to receive data) is 60000. You can set any of these timeouts to zero to disable the timeout. Configure connection and socket timeouts : 1 Unirest.setTimeouts(20000, 15000) 2. Customizable levels: Let’s set the number of connections and number maximum connections per route: .
  • 16. CUSTOMIZABLE TIMEOUT, LEVELS AND PROXY SETTINGS Proxy settings: You can set a proxy by invoking: .
  • 17. CUSTOMIZABLE DEFAULT HEADERS Default Request Headers You can set default headers that will be sent on every request: Unirest.setDefaultHeader("Accept-Language", "en-GB,en-US;q=0.9,en;q=0.81"); Clear Default Header: You can clear the default headers anytime with: Unirest.clearDefaultHeaders(); .
  • 18. Customizable HttpClient and HttpAsyncClient implementation You can explicitly set your own HttpClient and HttpAsyncClient implementations by using the following methods: Unirest.setHttpClient(httpClient); Unirest.setAsyncHttpClient(asyncHttpClient);
  • 19. AUTOMATIC JSON PARSING INTO A NATIVE OBJECT FOR JSON RESPONSES ➤ Unirest uses Jackson lib to parse JSON responses into java object. HttpResponse<JsonNode> jsonResponse = Unirest.post("http://httpbin.org/post") .header("accept", "application/json") .field("parameter", "value") .field("file", new File("/tmp/file")) .asJson(); .
  • 20. CUSTOMIZABLE BINDING, WITH MAPPING FROM RESPONSE BODY TO JAVA OBJECT Before an asObject(Class) or a .body(Object) invokation, is necessary to provide a custom implementation of the ObjectMapper interface. This should be done only the first time, as the instance of the ObjectMapper will be shared globally. For example, serializing Json fromto Object using the popular Jackson ObjectMapper takes only few lines of code. . // Only one time Unirest.setObjectMapper(new ObjectMapper() { private com.fasterxml.jackson.databind.ObjectMapper jacksonObjectMapper = new com.fasterxml.jackson.databind.ObjectMapper(); public <T> T readValue(String value, Class<T> valueType) { try { return jacksonObjectMapper.readValue(value, valueType); } catch (IOException e) { throw new RuntimeException(e); } }
  • 21. CUSTOMIZABLE BINDING, WITH MAPPING FROM RESPONSE BODY TO JAVA OBJECT // Response to Object HttpResponse<Book> bookResponse = Unirest.get("http://httpbin.org/books/1").asObject(Book.class); Book bookObject = bookResponse.getBody(); HttpResponse<Author> authorResponse = Unirest.get("http://httpbin.org/books/{id}/author") .routeParam("id", bookObject.getId()) .asObject(Author.class); Author authorObject = authorResponse.getBody(); // Object to Json HttpResponse<JsonNode> postResponse = Unirest.post("http://httpbin.org/authors/post") .header("accept", "application/json") .header("Content-Type", "application/json") .
  • 22. Demo Project: Java REST Client Using Unirest Java API ➤ Check this link: https://interviewbubble.com/demo-project-java- rest-client-using-unirest-java-api/