Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

How to call a Restful webservice in JAVA

Posted on 2013-11-21
8
Medium Priority
?
807 Views
Last Modified: 2013-12-11
Hello,
 How do you call a RestFul WebService from a Java Application.  I need to call the URL and Post some data to it and retrive the response.

I was told that the service is written in JAVA and uses the Spring framework

Thanks for your help
0
Comment
Question by:SiemensSEN
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
  • 2
8 Comments
 
LVL 28

Accepted Solution

by:
dpearson earned 1200 total points
ID: 39666703
Most people use a library like httpclient to handle this sort of web request.

There's details here on how to do a POST here:
http://hc.apache.org/httpcomponents-client-4.3.x/quickstart.html

Doug

(BTW it doesn't matter what the service itself is written in - to you it's just a URL that responds with some data).
0
 
LVL 36

Assisted Solution

by:mccarl
mccarl earned 800 total points
ID: 39667759
If the webservice is fairly simple (in terms of the data that you send and receive, and perhaps the number of different types of calls/methods that you need to invoke) than you can probably use Doug's suggestions (or even just plain old Java HttpUrlConnection functionality) quite easily.

However, if the use of the webservice is more complex, you might want to investigate using a higher level library to help out. These libraries can handle automatic conversion of JSON/XML data that might be sent/received over the webservice, error handling, etc. There are many options out there but 2 that I have experience in and think are relatively simple to work with are:

JAX-RS on Java 6+ (Jersey Implementation) - https://jersey.java.net/documentation/latest/client.html
Spring - http://docs.spring.io/spring/docs/3.1.x/spring-framework-reference/html/remoting.html#rest-client-access

Note I agree with Doug, that it doesn't matter what the webservice is written in. I mention Spring above because I think it is a good API to use for this sort of thing, NOT because the webservice uses it.


I know the above is a little bit brief, but if you decide that using a library such as these is the way to go, let us know and I can give you more detailed information.
0
 

Author Comment

by:SiemensSEN
ID: 39667961
Thank you .

I really will like to use spring. This RestAPI is simple now  but it will get more complicated in future releases.

I will read the links you sent me. However, if it would be very helpful  if you can provide any additional information. As always, I will Google to get more info

Thank you
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 

Author Comment

by:SiemensSEN
ID: 39668635
As an example.. I need to post the information below to the this rest URI
http://127.0.0.1:/api/data/add


{
        "message" => "[Wed Jun 26 22:13:22 2013] [client 10.10.10.100] PHP Fatal   ...."
        ,"@timestamp" => "2013-06-27T02:13:22.000Z"
        ,"m_level"        => "Info"
        ,"m_cat"           => "THIRD_PARTY"
        ,"m_cor"           => "None"
        ,"m_tenant"      => "xxxxx"
        ,"m_timezone" => "EDT"
        ,"m_tzoffset"    => "-04:00"
        ,"m_host"         =>"cassandra-03.boca.us"
        ,"m_path"         => "/var/log/messages"
        ,"m_type"         => "linux-syslog"
}

I already constructed  the json object.
0
 
LVL 36

Assisted Solution

by:mccarl
mccarl earned 800 total points
ID: 39668746
I will have some time later (it is the start of the weekend here and I don't get a lot of spare time over weekends to post on EE) to provide a more complete sample using the example you have given above, but to get you started it would be as simple as defining a bean in Spring for a RestTemplate object, and setting the list of messageConverters to use MappingJacksonHttpMessageConverter. You would probably also create a simple Java bean class to hold the fields in your message that you are sending, lets call it MessageDetail. Then you inject that restTemplate into your code and then the REST API call becomes as simple as...
MessageDetail message = new MessageDetail("[Wed Jun 26 22:13:22 2013] [error]...", "2013-06...", "Info", "THIRD_PARTY", ...);    // Note you don't even have to create the JSON yourself
URI location = restTemplate.postForLocation("http://127.0.0.1:/api/data/add", message);

Open in new window

Note that exactly which RestTemplate method you use depends on exactly how your REST service is implemented. The above assumes the REST standard where to add something you use the POST http method and the service returns a URI that describes where the newly added resource lives.
0
 

Author Comment

by:SiemensSEN
ID: 39670654
Thank you very much for the help. I will have a look at the RestTemplate and try to understand it.

However, I have to get a demo working this week. So, I will try use the HttpClient for now and later convert to REST.  Here is  my code snippet .. am I using the library correctly .  I will pass the JSON string and the URL to the class

public class Alarms 
{
     String url;
     public Alarms(String url)
     {
          this.url = url;
     }
     public void callRESTAPI(String jsonstring) throws IOException
     {
         CloseableHttpResponse response=null;
         CloseableHttpClient httpclient = HttpClients.createDefault();
         HttpClient c = new HttpClient();
         HttpPost p = new HttpPost(this.url);
         p.setEntity(new StringEntity(jsonstring,ContentType.create("application/json")));
         response = httpclient.execute(p);		
         System.out.println(response.getStatusLine());
                response.close();
}

Open in new window

0
 
LVL 28

Expert Comment

by:dpearson
ID: 39670864
I haven't tried running your code - but it looks pretty good.

Fortunately httpclient is so widely used there's lots of examples on the web.  If you run into trouble a quick google search will show you lots of examples.

E.g. There's a whole tutorial here:
http://hc.apache.org/httpcomponents-client-ga/tutorial/html/index.html

and this part has some more POST examples:
http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html#d5e171

Doug
0
 
LVL 36

Expert Comment

by:mccarl
ID: 39671316
And you can probably delete line 12 from the above code snippet. It's not doing anything useful.
0

Featured Post

The top UI technologies you need to be aware of

An important part of the job as a front-end developer is to stay up to date and in contact with new tools, trends and workflows. That’s why you cannot miss this upcoming webinar to explore the latest trends in UI technologies!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses

721 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question