Using a JSON web service from a Java client application

28,076

Solution 1

Apache HttpClient 4.0 is the best in the business and is moderately easy to learn.

If you want easier you could use HtmlUnit which imitates the behaviour of browsers so you could easily get the content (and parse it into Html, javascript and css, you could also execute javascript code on content so you could probably parse JSON files to using JSON.parse or any other equivalent functions) of any page on the web.

so for HtmlUnit here is a sample code:

WebClient wc = new WebClient(BrowserVersion.FIREFOX_3_6);
HtmlPage page = wc.getPage("http://urlhere");
page.executeJavaScript("JS code here");

but it maybe rather heavy for your requirements so a highly recommend the use of HttpClient library. I'm sure you could find many JSON libraries for java but here is one for you json-lib

Solution 2

I did it using a simple Java JSON libary. Use the Google library..

URL url = new URL("http://www.siteconsortium.com/services/hello.php");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

JSONParser parser=new JSONParser();
Object object = parser.parse(in);

JSONArray array = (JSONArray) object;        
JSONObject object2 = (JSONObject)array.get(0);
System.out.println(object2.get("hello")); 

If the webservice uses OAuth and an access token you can't use the above example though.

Share:
28,076
Gigatron
Author by

Gigatron

Updated on July 27, 2020

Comments

  • Gigatron
    Gigatron almost 4 years

    I am developing a client-side Java application that has a bit of functionality that requires getting data from some web services that transmit in JSON (some RESTful, some not). No JavaScript, no web browser, just a plain JAR file that will run locally with Swing for the GUI.

    This is not a new or unique problem; surely there must be some open source libraries out there that will handle the JSON data transmission over HTTP. I've already found some that will parse JSON, but I'm having trouble finding any that will handle the HTTP communication to consume the JSON web service.

    So far I've found Apache Axis2 apparently which might have at least part of the solution, but I don't see enough documentation for it to know if it will do what I need, or how to use it. Maybe part of the problem is that I don't have experience with web services so I'm not able to know a solution when I see it. I hope some of you can point me in the right direction. Examples would be helpful.