A simple Web service that contains the Jersey library and a Java client that sends JSON data

Source: Internet
Author: User
Tags readline
a simple Web service that contains the Jersey library and a Java client that sends JSON data

A simple Web service that contains the Jersey library and a Java client that sends JSON data preface environment Tools build Dynamic Web Project Create your Restservice class create Java Project as JSON Client Other Resource

preface Want to write this article tutorial the reason is very simple, before learning Web service when found that a lot of data on the examples are basically together, that is to say, the functional structure is very complete, copy paste is also very cool, But some of the details of the configuration and so on may have errors, and therefore delayed a long time this sample is basically crunchify translation version, but inside for web.xml configuration is somewhat different, crunchify that seems to be wrong (at least I was not able to use his run through) This article original, allow reprint but be sure to post this article link environment & Tools Jersey Jax-rs 2.0 RI Bundle after decompression, put all. jar files under Webcontent>web-inf>lib Json.jar java Version "1.8.0_40" Tomcat 8.0 Eclipse Luna Build dynamic Web Project name = "Simplerestwebservice" Create we B.xml, the contents are as follows:

<?xml version= "1.0" encoding= "UTF-8"?> <web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns= "Http://java.sun.com/xml/ns/javaee" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http:// Java.sun.com/xml/ns/javaee/web-app_3_0.xsd "id=" webapp_id "version=" 3.0 "> <display-name> simplerestwebservice</display-name> <servlet> <servlet-name>jersey REST service</servlet- Name> <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> <ini T-param> <param-name>jersey.config.server.provider.packages</param-name> <param- Value>simplerestwebservice</param-value> </init-param> <load-on-startup>1</load-on -startup> </servlet> <servlet-mapping> <servlet-name>jersey REST service</servlet- Name> <url-pattern>/api/*</url-pattern> </serVlet-mapping> </web-app> 

The main function of this sample web.xml is to map all the requests under webroot/api/to the Simplerestwebservice.restservice class to Create your Restservice class .

The contents are as follows:

Package simplerestwebservice;
Import Java.io.BufferedReader;
Import Java.io.InputStream;

Import Java.io.InputStreamReader;
Import Javax.ws.rs.GET;
Import javax.ws.rs.Produces;
Import Javax.ws.rs.Consumes;
Import Javax.ws.rs.POST;
Import Javax.ws.rs.Path;
Import Javax.ws.rs.core.MediaType;

Import Javax.ws.rs.core.Response; @Path ("/restservice") public class Restservice {@POST @Consumes (Mediatype.application_json) public Response J
        Son_restresponse (InputStream incomingdata) {StringBuilder jsonrest = new StringBuilder ();
            try {BufferedReader in = new BufferedReader (new InputStreamReader (Incomingdata));
            String line = null;
            while (line = In.readline ())!= null) {jsonrest.append (line);
        The catch (Exception e) {System.out.println ("Error parsing:-");

        } System.out.println ("Data Received:" + jsonrest.tostring ()); Return HTTP response Success return Response.Status. Entity (Jsonrest.tostring ()). build (); @GET @Produces (mediatype.text_plain) public String Sayplaintexthello () {return "Hello Simplerestwe
    Bservice "; The//This is called if XML am request @GET @Produces (mediatype.text_xml) public String Sayxmlhello
    () {return "<?xml version=\" 1.0\ "?>" + " 

This includes two kinds of HTTP requests, get and post, where I do intuitive testing with got, and then stamp Http://localhost:8080/simpleRestWebService/api/restService to see the results. The other one is post, which we later use to accept the request containing the JSON file. creating Java Project as a JSON client first writes a small JSON file as input, such as:

{"
    Tristan": {"
        name": "Tristan", "Age
        ": "
        University": "UESTC", "Hobby"
        : ["jog", "Ride"]
    }
}

can go to Webmaster tools to check if it is in line with the JSON format client class name = "Restclient" Client content as follows:

Package restserivceclient;
Import Java.io.BufferedReader;
Import Java.io.FileInputStream;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.io.OutputStreamWriter;
Import Java.net.URL;

Import java.net.URLConnection;

Import Org.json.JSONObject;
        public class Restclient {public static void main (string[] args) {string string = ""; try {//Step1:let ' s 1st read file from filesystem InputStream Clientinputstream = new FileInput
            Stream ("/home/tristan/workspace/source/iofiles/samplejson.js");
            InputStreamReader Clientreader = new InputStreamReader (clientinputstream);
            BufferedReader br = new BufferedReader (Clientreader);
            String Line;
            while (line = Br.readline ())!= null) {string = = line + \ n;
            } jsonobject jsonobject = new Jsonobject (string);

            System.out.println (Jsonobject); Step2:nowPass JSON File Data to REST Service try {URL url = new URL ("Http://localhost:8080/simpleRestW
                Ebservice/api/restservice ");
                URLConnection connection = Url.openconnection ();
                Connection.setdooutput (TRUE);
                Connection.setrequestproperty ("Content-type", "Application/json");
                Connection.setconnecttimeout (5000);
                Connection.setreadtimeout (5000);
                OutputStreamWriter out = new OutputStreamWriter (Connection.getoutputstream ());
                Out.write (Jsonobject.tostring ());
                Out.close ();

                System.out.println ("Ok~before");
                InputStreamReader Inreader = new InputStreamReader (Connection.getinputstream ());

                System.out.println ("Ok~reader");
                BufferedReader in = new BufferedReader (Inreader);
                System.out.println ("Ok~buffer");
  while (In.readline ()!= null) {}              System.out.println ("\nrest Service invoked successfully ...");
            In.close ();
                catch (Exception e) {System.out.println ("\nerror while calling REST Service");
            System.out.println (e);
        } br.close ();
        catch (Exception e) {e.printstacktrace ();
 }
    }
}

If you cannot connect to the server, there will only be "Ok~before" in the console and a exception hint other Resource can do web.xml configuration dictionaries The role and basic configuration of the Web.xml file

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.