apache wink rest learning (configuration, coding, invocation)

        I have recently come into contact with a new project. The remote interface in the project uses rest wink. In the past, this requirement was basically realized by webservice. Today, I specially conducted theoretical research and actual coding work on rest wink, so I recorded it for later use. Check it out. I saw a good article in the theoretical part, so I will quote it directly here. Article address: https://www.oschina.net/question/5189_8593


REST stands for Representational State Transfer, a set of architectural principles upon which the World Wide Web relies. Roy Fielding first introduced this concept in his doctoral thesis "Architectural Styles and the Design of Network-based Software Architectures". In his paper, Fielding identified five architectural principles for REST and the World Wide Web:
Addressability. Everything in REST is based on the concept of resources. A resource, unlike an object or other noun in OOP, is an abstraction that must be addressable or accessible via a URI.
Interface uniformity. Unlike SOAP or other standards, REST requires that the methods or verbs used to manipulate resources are not arbitrary. This means that developers of RESTful services can only use HTTP-supported methods such as GET, PUT, POST, DELETE, and so on. Therefore, there is no need to use a service description language such as WSDL.
Statelessness. To enhance scalability, the server side does not store client state information. This keeps the server from being tied to a specific client, and load balancing becomes much simpler. It also makes the server easier to monitor and more reliable.
Representational. Clients always interact with some representation of the resource, never directly with the resource itself. The same resource can also have multiple representations. In theory, any client holding a representation of a resource should have enough information to manipulate the underlying resource.
Connectedness. Any REST-based system should anticipate that clients need access to relevant resources and should include these resources in the returned resource representation. For example, the relevant steps in the sequence of operations for a particular RESTful service can be included as hyperlinks, allowing clients to access them as needed.


       Why do you need another Java standard? JAX-RS This new specification was defined to simplify REST-based Java development. It is primarily concerned with implementing RESTful services using Java annotations and Plain Old Java Objects (POJOs). While it is always possible to implement RESTful services using servlets, implementing business logic this way requires too many HTTP GET requests.
JAX-RS hides all HTTP and binds servlets to methods in Java classes. Annotations can also dynamically extract information from HTTP requests and map application-generated exceptions to HTTP response codes. For these reasons, JAX-RS is an efficient way to implement RESTful Java Web services.
     Now that I've covered REST and JAX-RS, I'll start talking about Apache Wink. Apache Wink 1.0 is a fully compliant implementation of the JAX-RS 1.0 specification designed from the ground up. It is easy to use and apply in production environments, and it provides features that enhance the core JAX-RS specification.
      The Apache Wink runtime architecture is a simple implementation of the JAX-RS 1.0 specification. Apache Wink is deployed in the Java Platform, Enterprise Edition (Java EE) environment and consists of the following three components:
Apache Wink RestServlet. RestServlet is configured in the Java EE web.xml descriptor file of the web application. This servlet acts as the main entry point for all HTTP Web service requests, dispatching request and response object instances to request handlers for further processing.
Request handler.RequestProcessor is the core Apache Wink engine, which is initialized by Apache Wink RestServlet. The request handler uses the request URI to find, match, and invoke the corresponding resource classes and methods. Any exception that occurs during request processing causes the RequestProcessor to call the Error Handler Chain to handle the exception.
Resources. In REST, any component or object that represents a Web service is called a resource. A resource allows data to be acquired and manipulated through one of its many manifestations. A POJO that implements a resource is called a resource class. The resource class further implements resource methods, which actually handle the underlying business logic.
Apache Wink logic diagram



 

The following is an example of exposing a remote interface to the outside world using rest wink today:

1. Take a screenshot of the required jar package



 

2. Configure web.xml

The configuration here includes the integration of rest wink and spring. I use screenshots for the code here, and the source code is in the attachment

 

3. Configure rest.xml



 

4. Write the interface class

package rest;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.json.JSONException;
import org.json.JSONObject;

import common.Logger;

/**
 * rest interface test case class
 * @author peak
 *
 */
@Path("/jeff/test")
public class RestWinkTest {
 private static Logger log=Logger.getLogger(RestWinkTest.class);
 
 /**
  * method description : Test rest interface POST method
  * @param type type
  * @param content additional content
  * @param info json format content
  * @return
  */
 @POST
 @Path("/testget/{type}/{content}")
 @Produces( MediaType.APPLICATION_JSON)
 public JSONObject testRestGetAPI(@PathParam("type") int type,@PathParam("content") String content,JSONObject info){
  log.info("The calling path is: http://localhost:8080/jeff /test/testget/ ---------- call method is POST");
  JSONObject resultJson = new JSONObject();
  resultJson=info;
  try {   
   resultJson.put("type", type);
   resultJson.put("content",content);
  } catch (JSONException e) {
   e.printStackTrace();
  }
  log.info("调用完成");
  return resultJson;
 }

 

/**
  * Method description: The local main method calls the remote interface test
  * @param agrs
  * @throws IOException
  */
 public static void main(String[] agrs) throws IOException{
  String reqUrl=" http://localhost:8080/rest /jeff/test/testget/2/ China";
  JSONObject inputobj=new JSONObject();
  HttpURLConnection conn=null;
  OutputStreamWriter opsw=null;
  InputStream inpus=null;
  ByteArrayOutputStream baops=null;
  try {
   //Parameter assembly
   inputobj.put( "key",MD5.MD5Encode("FRIST KEY!"));
   inputobj.put("value",MD5.MD5Encode(reqUrl));
   String inputjsonstr=inputobj.toString(); log.info
   (inputjsonstr);
   // Address invocation through the URL class under java.net
   URL url=new URL(reqUrl);
   conn=(HttpURLConnection)url.openConnection();
   conn.setRequestMethod("POST");
   //Set the timeout
   conn.setReadTimeout(10000);
   conn.setConnectTimeout(10000);
   //Set Return parameter and call parameter type
   conn.addRequestProperty("content-type","application/json");
   conn.setDoOutput(true);
   conn.setUseCaches(false);
   opsw=new OutputStreamWriter(conn.getOutputStream(),"UTF -8");
   opsw.write(inputjsonstr);
   opsw.flush();
   //Get the result returned by the remote interface and parse
   it inpus=conn.getInputStream();
   baops=new ByteArrayOutputStream();
   byte[] btbuffer=new byte[1024];
   int len=0;
   while ((len = input.read(btbuffer)) != -1)
            {
    baops.write(btbuffer, 0, len);
            }
            byte[] data = baops.toByteArray();
            log.info("调用完成,返回结果为:"+new String(data, "utf-8"));
  } catch (Exception e) {
   e.printStackTrace();
  }finally{
   if(opsw!=null)opsw.close();
   if(inpus!=null)inpus.close();
   if(baops!=null)baops.close();
  }  
 }

}

 

5. Remote interface test

The interface call I use is the restclient plug-in of firefox to call, see the following figure:



 



 

 

Notes:

Because of the limited time, I only wrote one post type for the interface class, and there are many other types, such as


The specific usage of these types is almost the same. I recommend an article, which has a good introduction, and I have read it very well.

Address:
 http://wenda.bmob.cn/?/question/51

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326413038&siteId=291194637