{"id":2060,"date":"2017-03-30T21:16:05","date_gmt":"2017-03-30T21:16:05","guid":{"rendered":"http:\/\/blog.paranoidprofessor.com\/?p=2060"},"modified":"2017-03-30T21:16:05","modified_gmt":"2017-03-30T21:16:05","slug":"restful-services-in-java-simple-client-example","status":"publish","type":"post","link":"https:\/\/blog.paranoidprofessor.com\/index.php\/2017\/03\/30\/restful-services-in-java-simple-client-example\/","title":{"rendered":"Restful services in Java &#8211; simple client example"},"content":{"rendered":"<p>I suppose that a restful server isn&#8217;t all that useful unless there is a way to query this information back and use it in some useful way.<\/p>\n<p>It is easy enough to test this out the server from the command line using the curl command. \u00a0Simply select the return type and select the URI.<\/p>\n<div id=\"attachment_2061\" style=\"width: 799px\" class=\"wp-caption alignnone\"><a href=\"http:\/\/blog.paranoidprofessor.com\/wp-content\/uploads\/2017\/02\/firstrestful-11.png\"><img aria-describedby=\"caption-attachment-2061\" decoding=\"async\" loading=\"lazy\" class=\"wp-image-2061 size-full\" src=\"http:\/\/blog.paranoidprofessor.com\/wp-content\/uploads\/2017\/02\/firstrestful-11.png\" width=\"789\" height=\"166\" srcset=\"https:\/\/blog.paranoidprofessor.com\/wp-content\/uploads\/2017\/02\/firstrestful-11.png 789w, https:\/\/blog.paranoidprofessor.com\/wp-content\/uploads\/2017\/02\/firstrestful-11-300x63.png 300w, https:\/\/blog.paranoidprofessor.com\/wp-content\/uploads\/2017\/02\/firstrestful-11-768x162.png 768w\" sizes=\"(max-width: 789px) 100vw, 789px\" \/><\/a><p id=\"caption-attachment-2061\" class=\"wp-caption-text\">curl -H &#8220;Accept: text\/plain&#8221; http:\/\/192.168.178.70:8080\/FirstRestful\/Communicate\/hello<\/p><\/div>\n<p>&nbsp;<\/p>\n<div id=\"attachment_2062\" style=\"width: 790px\" class=\"wp-caption alignnone\"><a href=\"http:\/\/blog.paranoidprofessor.com\/wp-content\/uploads\/2017\/02\/firstrestful-12.png\"><img aria-describedby=\"caption-attachment-2062\" decoding=\"async\" loading=\"lazy\" class=\"wp-image-2062 size-full\" src=\"http:\/\/blog.paranoidprofessor.com\/wp-content\/uploads\/2017\/02\/firstrestful-12.png\" width=\"780\" height=\"166\" srcset=\"https:\/\/blog.paranoidprofessor.com\/wp-content\/uploads\/2017\/02\/firstrestful-12.png 780w, https:\/\/blog.paranoidprofessor.com\/wp-content\/uploads\/2017\/02\/firstrestful-12-300x64.png 300w, https:\/\/blog.paranoidprofessor.com\/wp-content\/uploads\/2017\/02\/firstrestful-12-768x163.png 768w\" sizes=\"(max-width: 780px) 100vw, 780px\" \/><\/a><p id=\"caption-attachment-2062\" class=\"wp-caption-text\">curl -H &#8220;Accept: application\/xml&#8221; http:\/\/192.168.178.70:8080\/FirstRestful\/Communicate\/hello<\/p><\/div>\n<p>This is the best starting point as we can pretty much guarantee that the server is working. Should any problems occur during the development of the client we can pretty much point to the client as the culprit.<\/p>\n<h2>Java client<\/h2>\n<p>My first web services client will be essentially just a plain old java program. \u00a0Although I am using java for my client I can easily imagine that there are some systems that were programmed in some older languages that use also use restful services in this same manner. \u00a0Not only communicate with a web server but to provide an easy way to enhance those systems with abilities that were didn&#8217;t exist when they were created (I am looking at you <a href=\"https:\/\/sourceforge.net\/p\/open-cobol\/discussion\/contrib\/thread\/2b474086\/\" target=\"_blank\">COBOL <\/a>).<\/p>\n<p>Jersey makes the process of making restful calls easy from Java. \u00a0The restConnect method groups together the necessary logic for accessing a URI that is passed in.<\/p>\n<p>Once these steps are done the object is a WebTarget is initialized and it is possible to call the restful service.<\/p>\n<p>In this example client example I use use three slightly different methods for setting up the URI. \u00a0The two more flexible calls (lines 68 &#8211; 78) setup a base URI and then adds to the path. \u00a0This might be the best way if quite a few similar calls were necessary.<\/p>\n<p>When doing the restful calls you also pass in the datatype that you wish to be returned back. \u00a0This then does the proper call to the server to get the correct return type.<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n\/**\r\n * \r\n *\/\r\npackage com.acmesoft;\r\n\r\nimport java.io.StringReader;\r\nimport java.net.URI;\r\n\r\nimport javax.ws.rs.client.Client;\r\nimport javax.ws.rs.client.ClientBuilder;\r\nimport javax.ws.rs.client.WebTarget;\r\nimport javax.ws.rs.core.MediaType;\r\nimport javax.ws.rs.core.Response;\r\nimport javax.ws.rs.core.UriBuilder;\r\nimport javax.xml.bind.JAXBContext;\r\nimport javax.xml.bind.JAXBException;\r\nimport javax.xml.bind.Unmarshaller;\r\n\r\nimport org.glassfish.jersey.client.ClientConfig;\r\n\r\npublic class TestClient \r\n{\r\n\tString uribase = &quot;http:\/\/192.168.178.70:8080\/FirstRestful&quot;;\r\n\tString urifull = uribase + &quot;\/Communicate\/hello&quot;;\r\n\r\n\tpublic void showMagazine(String desc, magazine value)\r\n\t{\r\n\t\tSystem.out.println(&quot;\\n&quot; + desc );\r\n\t\tSystem.out.println(&quot;year &quot;  + value.getYear());\r\n\t\tSystem.out.println(&quot;month &quot; + value.getMonth());\r\n\t\tSystem.out.println(&quot;price &quot; + value.getPrice());\r\n\t\tSystem.out.println(&quot;title &quot; + value.getTitle());\r\n\t}\r\n\t\r\n\tpublic magazine convertXmlToMag(String xmlstring)\r\n\t{\r\n\t\tmagazine converted = null;\r\n\t\tJAXBContext jc = null;\r\n\t\ttry {\r\n\t\t\tjc = JAXBContext.newInstance(magazine.class);\r\n\t\t\tUnmarshaller unmarshaller = jc.createUnmarshaller();\r\n\t\t\tStringReader reader = new StringReader(xmlstring);\r\n\t\t\tconverted = (magazine) unmarshaller.unmarshal(reader);\t\r\n\t\t}\r\n\t\tcatch (JAXBException ex)\r\n\t\t{\r\n\t\t\tex.printStackTrace();\r\n\t\t}\r\n\t\treturn converted;\r\n\t}\r\n\t\r\n\tpublic WebTarget restConnect(String targetUrl)\r\n\t{\r\n\t\tURI uri = UriBuilder.fromUri(targetUrl).build();\r\n\t\tClientConfig config = new ClientConfig();\r\n\t\tClient client = ClientBuilder.newClient(config);\r\n\t\tWebTarget target = client.target(uri);\r\n\t\treturn target;\r\n\t}\r\n\t\r\n\tpublic TestClient()\r\n\t{\r\n\t\t\/\/ example 1\r\n\t\tWebTarget target = restConnect(urifull);\r\n\t\tString plainAnswer = target.request().accept(MediaType.TEXT_PLAIN).get(String.class);\r\n\t\tSystem.out.println(&quot;raw (text)data&quot;);\r\n\t\tSystem.out.println(plainAnswer);\r\n\t\tSystem.out.println(&quot;&quot;);\r\n\t\t\r\n\t\t\/\/ example 2\/3 setup\r\n\t\tClientConfig config1 = new ClientConfig();\r\n\t\tClient client1       = ClientBuilder.newClient(config1);\r\n\t\tWebTarget target1    = client1.target(uribase);\r\n\r\n\t\t\/\/ example 2\r\n\t\tString xmlAnswer = target1.path(&quot;\/&quot;).path(&quot;Communicate&quot;).path(&quot;\/hello&quot;).request().accept(MediaType.APPLICATION_XML).get(String.class);\r\n\t\tmagazine converted = convertXmlToMag(xmlAnswer);\r\n\t\tSystem.out.println(xmlAnswer);\r\n\t\tshowMagazine(&quot;xml text data&quot;, converted);\r\n\t\t\r\n\t\t\/\/ example 3\r\n\t\tmagazine xmlobj = target1.path(&quot;\/Communicate\/hello&quot;).request().accept(MediaType.APPLICATION_XML).get(magazine.class);\r\n\t\tshowMagazine(&quot;pure xml object&quot;, xmlobj);\r\n\t}\r\n\t\r\n\tpublic static void main(String[] args) \r\n\t{\r\n\t\tnew TestClient();\r\n\t}\r\n}\r\n<\/pre>\n<p>Below is the magazine class with the appropriate markups to easily do the JAXB conversion between plain old java objects and XML.<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npackage com.acmesoft;\r\n\r\nimport javax.xml.bind.annotation.XmlAccessorType;\r\nimport javax.xml.bind.annotation.XmlElement;\r\nimport javax.xml.bind.annotation.XmlRootElement;\r\nimport javax.xml.bind.annotation.XmlAccessType;\r\n\r\n@XmlRootElement(name=&quot;Magazine&quot;)\r\n@XmlAccessorType(XmlAccessType.FIELD)\r\npublic class magazine {\r\n\r\n\t\/\/ Microsoft Exchange values \r\n\t@XmlElement(name=&quot;Year&quot;)\r\n\tprivate  int year; \r\n\r\n\t@XmlElement(name=&quot;Month&quot;)\r\n\tprivate  int month; \r\n\r\n\t@XmlElement(name=&quot;Title&quot;)\r\n\tprivate   String title; \r\n\r\n\t@XmlElement(name=&quot;Price&quot;)\r\n\tprivate   double price;\r\n\r\n\tpublic magazine()\r\n\t{\r\n\t}\r\n\tpublic magazine(int year, int month, String title, double price)\r\n\t{\r\n\t\tthis.year = year;\r\n\t\tthis.month = month;\r\n\t\tthis.title = title;\r\n\t\tthis.price = price;\r\n\t}\r\n\r\n\tpublic int getYear()\r\n\t{\r\n\t\treturn year;\r\n\t}\r\n\tpublic void setYear(int value)\r\n\t{\r\n\t\tthis.year= value;\r\n\t}\r\n\r\n\tpublic int getMonth()\r\n\t{\r\n\t\treturn month;\r\n\t}\r\n\tpublic void setMonth(int value)\r\n\t{\r\n\t\tthis.month= value;\r\n\t}\r\n\r\n\tpublic String getTitle()\r\n\t{\r\n\t\treturn title;\r\n\t}\r\n\tpublic void setTitle(String value)\r\n\t{\r\n\t\tthis.title = value;\r\n\t}\r\n\r\n\tpublic double getPrice()\r\n\t{\r\n\t\treturn price;\r\n\t}\r\n\tpublic void setPrice(double value)\r\n\t{\r\n\t\tthis.price = value;\r\n\t}\r\n}\r\n<\/pre>\n<p>The flexibility of the restful API\u00a0calls \u00a0is pretty amazing. The first example (lines 62-67) shows how easy it can be to call a restful service. \u00a0Nothing is all that surprising as the server is passing back text and that text is assigned to a string.<\/p>\n<p>The second example is slightly more useful\u00a0as the return data is XML\u00a0formatted and it is possible to <a href=\"http:\/\/blog.paranoidprofessor.com\/index.php\/2016\/10\/21\/fun-with-xml-a-jaxb-example\/\" target=\"_blank\">convert that into a java object using JAXB<\/a>. \u00a0XML\u00a0data is still text data and it shouldn&#8217;t be amazing that text data is returned and assigned to a string. \u00a0Manually parsing out the data from an XML structure is really painful so I created the method <strong><em>convertXmlToMag<\/em><\/strong>\u00a0to parse the XML into a java object.<\/p>\n<p>The third example is by far the most useful example. \u00a0The restful server returns XML data but when making the restful call instead of passing in a string class I pass in a magazine class. \u00a0Thus the restful call returns the magazine object directly. \u00a0This also isn&#8217;t magic as the class does need to be defined when compiling the client but that is pretty much to be expected. \u00a0If the server does have certain types of data you wish to query then the client would already have similar or identical structured objects.<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\r\nraw (text)data\r\nHello World\r\nHaving a great time!\r\n\r\n200\r\n&lt;Magazine&gt;&lt;Year&gt;2016&lt;\/Year&gt;&lt;Month&gt;6&lt;\/Month&gt;&lt;Title&gt;Economist&lt;\/Title&gt;&lt;Price&gt;9.99&lt;\/Price&gt;&lt;\/Magazine&gt;\r\n\r\nxml text data\r\nyear 2016\r\nmonth 6\r\nprice 9.99\r\ntitle Economist\r\n\r\npure xml object\r\nyear 2016\r\nmonth 6\r\nprice 9.99\r\ntitle Economist\r\n<\/pre>\n<div class=\"\"><a href=\"http:\/\/blog.paranoidprofessor.com\/wp-content\/downloads\/FirstRestfulClient.tar.gz\" target=\"_self\" class=\"emd_dl_blue\">Download files<\/a><\/div>        <style type=\"text\/css\">\r\n    .emd_dl_blue {\r\n        -moz-box-shadow:inset 0px 1px 0px 0px #bbdaf7;\r\n        -webkit-box-shadow:inset 0px 1px 0px 0px #bbdaf7;\r\n        box-shadow:inset 0px 1px 0px 0px #bbdaf7;\r\n        background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #79bbff), color-stop(1, #378de5) );\r\n        background:-moz-linear-gradient( center top, #79bbff 5%, #378de5 100% );\r\n        filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#79bbff', endColorstr='#378de5');\r\n        background-color:#79bbff;\r\n        -webkit-border-top-left-radius:0px;\r\n        -moz-border-radius-topleft:0px;\r\n        border-top-left-radius:0px;\r\n        -webkit-border-top-right-radius:0px;\r\n        -moz-border-radius-topright:0px;\r\n        border-top-right-radius:0px;\r\n        -webkit-border-bottom-right-radius:0px;\r\n        -moz-border-radius-bottomright:0px;\r\n        border-bottom-right-radius:0px;\r\n        -webkit-border-bottom-left-radius:0px;\r\n        -moz-border-radius-bottomleft:0px;\r\n        border-bottom-left-radius:0px;\r\n        text-indent:0;\r\n        border:1px solid #84bbf3;\r\n        display:inline-block;\r\n        color:#ffffff !important;\r\n        font-family:Georgia;\r\n        font-size:15px;\r\n        font-weight:bold;\r\n        font-style:normal;\r\n        height:41px;\r\n        line-height:41px;\r\n        width:153px;\r\n        text-decoration:none;\r\n        text-align:center;\r\n        text-shadow:1px 1px 0px #528ecc;\r\n    }\r\n    .emd_dl_blue:hover {\r\n        background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #378de5), color-stop(1, #79bbff) );\r\n        background:-moz-linear-gradient( center top, #378de5 5%, #79bbff 100% );\r\n        filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#378de5', endColorstr='#79bbff');\r\n        background-color:#378de5;\r\n    }.emd_dl_blue:active {\r\n        position:relative;\r\n        top:1px;\r\n    }\r\n    <\/style>\n","protected":false},"excerpt":{"rendered":"<p>I suppose that a restful server isn&#8217;t all that useful unless there is a way to query this information back and use it in some useful way. It is easy enough to test this out the server from the command &hellip; <a href=\"https:\/\/blog.paranoidprofessor.com\/index.php\/2017\/03\/30\/restful-services-in-java-simple-client-example\/\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[20,3],"tags":[12,36,88],"_links":{"self":[{"href":"https:\/\/blog.paranoidprofessor.com\/index.php\/wp-json\/wp\/v2\/posts\/2060"}],"collection":[{"href":"https:\/\/blog.paranoidprofessor.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.paranoidprofessor.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.paranoidprofessor.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.paranoidprofessor.com\/index.php\/wp-json\/wp\/v2\/comments?post=2060"}],"version-history":[{"count":19,"href":"https:\/\/blog.paranoidprofessor.com\/index.php\/wp-json\/wp\/v2\/posts\/2060\/revisions"}],"predecessor-version":[{"id":2245,"href":"https:\/\/blog.paranoidprofessor.com\/index.php\/wp-json\/wp\/v2\/posts\/2060\/revisions\/2245"}],"wp:attachment":[{"href":"https:\/\/blog.paranoidprofessor.com\/index.php\/wp-json\/wp\/v2\/media?parent=2060"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.paranoidprofessor.com\/index.php\/wp-json\/wp\/v2\/categories?post=2060"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.paranoidprofessor.com\/index.php\/wp-json\/wp\/v2\/tags?post=2060"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}