This Post explains
the Jersey client API’s to create RESTful java client GET, POST and PUT request
to Rest API service.
1. Jersey Client Dependency
Declare the fallowing dependencies in the pom.xml file.
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.5.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.5.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3</version>
</dependency>
2.
GET Request, POST Request, PUT Request
REST Service Example
refer before post
package
com.sparktheprograms.jersey;
import
javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import
javax.ws.rs.Produces;
import
javax.ws.rs.core.MediaType;
import
javax.ws.rs.core.Response;
@Path("api")
public class JerseyService {
@GET
@Produces(MediaType.TEXT_PLAIN)
public String helloMessage()
{
return "Hey, This is
Jersey !";
}
@GET
@Path("/getMessage")
@Produces(MediaType.APPLICATION_JSON)
public Message message() {
Message
message = new Message();
message.setSite("www.9threes.com");
message.setMessage("JERSEY Sample
Application");
return message;
}
@POST
@Path("/postMessage")
@Consumes(MediaType.APPLICATION_JSON)
public Response
createMessageJson(Message message) {
String
data = "Message
Saved"+message;
return Response.status(200).entity(data).build();
}
@PUT
@Path("/putMessage")
@Consumes(MediaType.APPLICATION_JSON)
public Response
putMessage(Message msg)
{
String
data = "Message
Saved"+msg;
return Response.status(200).entity(data).build();
}
}
3. Jersey Client to
send GET Request, Post Request and PUT Request to Jersey Service
then jersey service returned the Response to Jersey Client.
package
com.sparktheprograms.jersey.client;
import
javax.ws.rs.client.Client;
import
javax.ws.rs.client.ClientBuilder;
import
javax.ws.rs.client.Entity;
import
javax.ws.rs.client.WebTarget;
import
javax.ws.rs.core.GenericType;
import
javax.ws.rs.core.MediaType;
import
javax.ws.rs.core.Response;
import
com.google.gson.Gson;
import
com.sparktheprograms.jersey.Message;
public class JerseyClient {
public static final String baseUri = "http://localhost:8888/JerseySampleApp/rest/api";
private Client client = null;
private WebTarget target = null;
public JerseyClient() {
client = ClientBuilder.newClient();
target = client.target(baseUri);
}
public void reloadUri() {
target = null;
target = client.target(baseUri);
}
public void getRequest() {
target = target.path("/getMessage");
// GET Request from Jersey Client
Response
response = target.request(MediaType.APPLICATION_JSON)
.get(Response.class);
if(response.getStatus()
== 200) {
Message
message = response.readEntity(new GenericType<Message>() {});
System.out.println(message.getSite());
}
}
public void postRequest() {
reloadUri();
String
input ="{\"site\":\"www.9threes.com\",\"message\":\"is
new domain\"}";
target = target.path("/postMessage");
// POST Request from Jersey Client
Response
response = target.request(MediaType.APPLICATION_JSON)
.post(Entity.entity(input, MediaType.APPLICATION_JSON),Response.class);
System.out.println(response);
if(response.getStatus()
== 200) {
System.out.println("post
success");
}
}
public void
postRequestUsingGson() {
reloadUri();
target = target.path("/postMessage");
Gson
gson = new Gson();
Message
msg = new Message();
msg.setSite("9threes");
msg.setMessage("its a new
Blog");
String
input = gson.toJson(msg);
//POST Request from jersey Client Using GSON
Response
response = target.request(MediaType.APPLICATION_JSON)
.post(Entity.entity(input, MediaType.APPLICATION_JSON),Response.class);
System.out.println(response);
if(response.getStatus()
== 200) {
System.out.println("post request
using Json is Success");
}
}
public void putRequest() {
reloadUri();
target = target.path("putMessage");
String
input ="{\"site\":\"www.9threes.com\",\"message\":\"is
new domain\"}";
//PUT Request from Jersey Client Example
Response
response = target.request(MediaType.APPLICATION_JSON)
.put(Entity.entity(input, MediaType.APPLICATION_JSON),Response.class);
System.out.println(response);
if(response.getStatus()
== 200) {
System.out.println("put request
using Json is Success");
}
}
public static void main(String args[]) throws Exception {
try {
JerseyClient
jerseyClient = new JerseyClient();
jerseyClient.getRequest();
jerseyClient.postRequest();
jerseyClient.postRequestUsingGson();
jerseyClient.putRequest();
}
catch(Exception e) {
System.out.println(e);
}
}
}
Output of above Jersey
client Example
In the above Jersey
client example example implemented the GET Request , POST Request and PUT Request Methods. I implemented two types of methods for POST Request
above jersey Client Example ,one method is implemented with JSON data and second
method is implemented using GSON API for Converting the JAVA POJO object into
JSON format for Jersey Service.
Message message = response.readEntity(new GenericType() {}); //This line throws an Error of getRequest() ....kindly fix this....IDE suggests add cast to response.......fix this error pls....ASAP.
ReplyDeleteGreat Article
Deleteandroid based projects
Java Training in Chennai
Project Center in Chennai
Java Training in Chennai
projects for cse
The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training
How to select the value of baseUri....In my project....package name is "com"...project name is suppose"RestConsumeExample" running on port 8080 then ?
ReplyDeletehttp://localhost:8080/RestConsumeExam/jaxrs/api...........I am getting output as "Hey this is Jersey".....but i try to invoke another like get /put through url......exception comes....how to get the output what u had got.....should i run the application or the client only on server ?
ReplyDeleteđồng tâm
ReplyDeletegame mu
cho thuê nhà trọ
cho thuê phòng trọ
nhac san cuc manh
số điện thoại tư vấn pháp luật miễn phí
văn phòng luật
tổng đài tư vấn pháp luật
dịch vụ thành lập công ty trọn gói
64 nước cờ trên bàn thương lượng ebook
mbp là gì
thuyết erg
các nghịch lý nổi tiếng
chi square test là gì
nghệ thuật nói chuyện trước công chúng dale carnegie
định lý coase
học thuyết kỳ vọng của victor vroom
chiến thắng con quỷ trong bạn audio
điểm cân bằng nash
- Cho dù Sở Giao thông có giao quyền xây dựng và kinh doanh cao tốc cho An Đô, nhưng 400 triệu đó. Ha ha, Quốc Đống, miệng chú không nhỏ nhỉ. Một năm An Đô thu được bao nhiêu mà dồn 400 triệu vào, như vậy cán bộ công chức còn muốn ăn cơm không?
Thái Chánh Dương cười khổ một tiếng.
- Chính quyền thành phố không muốn bỏ tiền thì có thể dùng cách BOT. Bây giờ trên thế giới hay dùng cách này, nó cũng hợp với tình hình An Đô. Đường cao tốc này đi thông qua Huyện Hoa Dương – huyện có kinh tế phát triển nhất An Đô, lại là con đường nhất định phải tới sân bay. Bây giờ việc di chuyển rất ùn tắc. Em nghe nói Cục Hàng không dân dụng đã nói chuyện này với Tỉnh ủy, Ủy ban nhân dân tỉnh, vừa lúc có thể nhân cơ hội này.
Triệu Quốc Đống lạnh nhạt nói.
- Cách BOT?
Thái Chánh Dương trầm ngâm một chút. Y biết cách này, đó chính là đổi quyền khai thác, kinh doanh trong mấy năm để đổi lấy tài chính xây dựng.
- Bây giờ ở Trung Quốc hình như chưa làm như vậy mà.
- Sao chưa có, nhà máy điện ở Quảng Tây không phải dùng cách nào sao? Hơn nữa còn là tám năm về trước, chẳng qua áp dụng BOT vào xây dựng cao tốc thì chưa có mà thôi. Chẳng lẽ Thành phố An Đô chúng ta không thể đi trước? Bí thư Ninh Pháp từ khu phát triển nhất ở duyên hải, tư tưởng của Bí thư Ninh vượt xa chúng ta. Em nghĩ cách này sẽ được Bí thư Ninh chú ý.
Nếu như nói câu trước của Triệu Quốc Đống chỉ làm Thái Chánh Dương động tâm, nhưng hai câu cuối lại làm Thái Chánh Dương quyết định thử một lần xem sao?
Great Article
ReplyDeleteFinal Year Project Domains for CSE
Project Centers in Chennai
JavaScript Training in Chennai
JavaScript Training in Chennai
Hmm, it seems like your site ate my first comment (it was extremely long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I as well as an aspiring blog writer, but I’m still new to the whole thing. Do you have any recommendations for newbie blog writers? I’d appreciate it.
ReplyDeleteAdvanced AWS Course Interview Questions And Answers, Top 250+AWS Jobs Interviews Questions and Answers 2018
Advanced AWS Jobs Interview questions and answers |Best Top 110 AWS Interview Question and Answers – india
I appreciate your efforts because it conveys the message of what you are trying to say. It's a great skill to make even the person who doesn't know about the subject could able to understand the subject . Your blogs are understandable and also elaborately described. I hope to read more and more interesting articles from your blog. All the best.
ReplyDeleterpa training in bangalore
rpa training in chennai
rpa training in pune
best rpa training in bangalore
Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging.
ReplyDeleteBest Devops Training in pune
Devops Training in Bangalore
Power bi training in Chennai
Come in and win right now. best slot machines Do not lose your luck.
ReplyDeleteYou truly did more than visitors’ expectations. Thank you for rendering these helpful, trusted, edifying and also cool thoughts on the topic to Kate
ReplyDeletepython Course in Pune
python Course institute in Chennai
python Training institute in Bangalore
Wow amazing to read this post
ReplyDeleteBest power BI training course in chennai
Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging
ReplyDeletehonor mobile service centre in Chennai
honor service center near me
honor service
honor service centres in chennai
honor service center velachery
honor service center in vadapalani
Great job done. Excellent post for the freshers. Keep updating it.
ReplyDeleteTOEFL Coaching in Chennai
TOEFL Coaching Centres in Chennai
German Courses in Chennai
Best IELTS Coaching in Chennai
learn Japanese in Chennai
spanish language classes in chennai
TOEFL Coaching in Anna Nagar
TOEFL Coaching in Tnagar
disable apache directory listing
ReplyDeletewhat is postfix
laravel clear cache
web hosting company in jaipur
Install php opcache
Attend The Python training in bangalore From ExcelR. Practical Python training in bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Python training in bangalore.
ReplyDeletepython training in bangalore
Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
ReplyDeletePython Training in Electronic City
I want to know more about American eagle credit card login
ReplyDeleteFlying Shift - Packers & Movers in Bhopal
ReplyDeletenice blog
ReplyDeleteget best placement at VSIPL
get digital marketing services
seo network point
Nice information, want to know about Selenium Training In Chennai
ReplyDeleteSelenium Training In Chennai
Data Science Training In Chennai
Protractor Training in Chennai
jmeter training in chennai
Rpa Training Chennai
Rpa Course Chennai
Selenium Training institute In Chennai
Python Training In Chennai
ReplyDeleteRpa Training in Chennai
Rpa Course in Chennai
Blue prism training in Chennai
Data Science Training In Chennai
Data Science Course In Chennai
Data Science Course In Chennai
Really it was an awesome article,very interesting to read.You have provided an nice article,Thanks for sharing.devops Training in Bangalore
ReplyDeleteThese provided information was really so nice,thanks for giving that post and the more skills to develop after refer that post.Amazon web services Training in Bangalore
ReplyDeleteEnroll today to get free access to our live demo session which is a great opportunity to interact with the trainer directly which is a placement based Salesforce training India with job placement and certification . Get salesforce training in affordable cost from a best computer institute.
ReplyDeleteGreat post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.
ReplyDeleteRobotic Process Automation (RPA) Training in Chennai | Robotic Process Automation (RPA) Training in anna nagar | Robotic Process Automation (RPA) Training in omr | Robotic Process Automation (RPA) Training in porur | Robotic Process Automation (RPA) Training in tambaram | Robotic Process Automation (RPA) Training in velachery
It's very useful article with informative and insightful content and i had good experience with this information.Enroll today to get free access to our live demo session which is a great opportunity to interact with the trainer directly which is a placement based Salesforce training India with job placement and certification . I strongly recommend my friends to join this Salesforce training institutes in hyderabad practical course, great curriculum Salesforce training institutes in Bangalore with real time experienced faculty Salesforce training institutes in Chennai. Never delay to enroll for a free demo at Salesforce training institutes in Mumbai who are popular for Salesforce training institutes in Pune.
ReplyDelete
ReplyDeleteThat is nice article from you , this is informative stuff . Hope more articles from you . I also want to share some information about devops training in pune
Facebook Video Downloader HD is an Android mobile app that offers the easiest way to download videos from Facebook.
ReplyDeleteThis comment has been removed by the author.
ReplyDelete
ReplyDeleteYour work is very good and I appreciate you and hopping for some more informative posts. ExcelR Data Science Course In Pune
Good blog, it's really very informative, do more blogs under good concepts.
ReplyDeletewhat is use of python
ccna career opportunities
is python good for web development
skills required for machine learning
data science questions and answers pdf
seo questions and answers
Excellent blog..! This is the best for my development and keep updating...
ReplyDeleteJMeter Training in Chennai
Appium Training in Chennai
Appium Online Training
Appium Training in Coimbatore
JMeter Training in Coimbatore
Soft Skills Training in Chennai
Male fertility doctor in chennai
ReplyDeleteStd clinic in chennai
Erectile dysfunction treatment in chennai
Premature ejaculation treatment in chennai
Web Development Company
ReplyDeleteMobile app development
Android app development company
ios app development
Thanks for posting the best information and the blog is very informative.python course in Bangalore
ReplyDeleteInformative blog
ReplyDeleteData Science Course in Pune
hybrid app development in usa
ReplyDeletephp web development in usa
python web development in usa
angular js development in usa
wordpress development company in usa
hybrid app development in usa
ReplyDeletephp web development in usa
python web development in usa
angular js development in usa
wordpress development company in usa
Hello Guest,
ReplyDeleteAwesome post, really helpful, Thanks for sharing...
DevOps Training in Hyderabad
DevOps Course in Hyderabad