REST with Java (JAX-RS) using Jersey

項目總體結構以下:

  1. pom.xml:

<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  < modelVersion>4.0.0</modelVersion >
  < groupId> rest</ groupId>
  < artifactId> rest.jersey</ artifactId>
  < packaging> war</ packaging>
  < version> 0.0.1-SNAPSHOT</ version>
  < name> rest.jersey Maven Webapp</ name>
  < url> http://maven.apache.org</ url>
  < dependencies>
    <dependency >
      <groupId >junit</groupId>
      <artifactId >junit</artifactId>
      <version >3.8.1 </version >
      <scope >test </scope >
    </dependency >
   
    <dependency >
            <groupId >org.glassfish.jersey.core </groupId >
            <artifactId >jersey-client </artifactId >
            <version >2.22.1 </version >
     </dependency >
   
    <dependency >
            <groupId >org.glassfish.jersey.core </groupId >
            <artifactId >jersey-server </artifactId >
            <version >2.22.1 </version >
     </dependency >
   
    <dependency >
            <groupId >org.glassfish.jersey.core </groupId >
            <artifactId >jersey-common </artifactId >
            <version >2.22.1 </version >
     </dependency >
   
    <dependency >
            <groupId >org.glassfish.jersey.containers </groupId >
            <artifactId >jersey-container- servlet</ artifactId>
            <version >2.22.1 </version >
     </dependency >
     
     <dependency >
            <groupId >org.glassfish.jersey.containers </groupId >
           <artifactId >jersey-container- servlet-core</artifactId >
            <version >2.22.1 </version >
     </dependency >
     
     <dependency >
            <groupId >javax.ws.rs </groupId >
            <artifactId >javax.ws.rs- api</ artifactId>
            <version >2.0.1 </version >
     </dependency >
     
     <dependency >
            <groupId >org.json </groupId >
            <artifactId >json</artifactId>
            <version >20151123 </version >
     </dependency >
     

     
   
  </ dependencies>
  < build>
    <finalName >rest.jersey </finalName >
  </ build>
</project>

2.web.xml:

<?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>Archetype Created Web Application </display-name >
     <servlet >
            <servlet-name >Jersey Web Application </servlet-name >
           <servlet-class >org.glassfish.jersey.servlet.ServletContainer </servlet-class >
            <init-param >
                 <param-name> jersey.config.server.provider.packages</param-name >
            <param-value >first </param-value >
            </init-param >
           
            <load-on-startup >1 </load-on-startup >
     </servlet >
     <servlet-mapping >
            <servlet-name >Jersey Web Application </servlet-name >
            <url-pattern >/first/* </url-pattern >
     </servlet-mapping >
</web-app>

3.first.C2FClient.java:

   

package first;

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

@Path("/c2fservice")
public class C2FService {

     //http://localhost:8080/rest.jersey/first/c2fservice
     @GET
     // @Produces(MediaType.APPLICATION_XML)
     @Produces(MediaType.TEXT_XML)
     public String convertC2F() {

          Double celsius = 36.9;// ['selsɪəs]攝氏
          Double fahrenheit = (celsius * 9 / 5) + 32;// ['færən'haɪt]華氏溫度

          String result = "@Produces(MediaType.APPLICATION_XML): 攝氏轉華氏: " + fahrenheit;
          return "<c2fservice>" + "<celsius>" + celsius + "</celsius>" + "<c2foutput>" + result + "</c2foutput>"
                    + "</c2fservice>";
     }

     //http://localhost:8080/rest.jersey/first/c2fservice/30
     @Path("{c}")
     @GET
     @Produces({MediaType.APPLICATION_XML,MediaType.TEXT_XML})
     public String convertCtoFfromInput(@PathParam("c") Double celsius) {
          Double fahrenheit = (celsius * 9 / 5) + 32;

          String result = "@Produces(MediaType.APPLICATION_XML):  攝氏轉華氏 : " + fahrenheit;
          return "<c2fservice>" + "<celsius>" + celsius + "</celsius>" + "<c2foutput>" + result + "</c2foutput>"
                    + "</c2fservice>";
     }
     
}

    而後在瀏覽器端輸入:http://localhost:8080/rest.jersey/first/c2fservice,頁面端則輸出convertC2F() 方法的返回值;java

    若是在瀏覽器端輸入:http://localhost:8080/rest.jersey/first/c2fservice/98,頁面端則輸出convertCtoFfromInput ()方法的返回值;web

    也可使用javax.ws.rs.client來建立一個客戶端來測試 ,以下:apache

4.client.C2FClient_javax_ws_rs.java:

package client;


import java.net.URI;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;

import org.glassfish.jersey.client.ClientConfig;

public class CFClient_javax_ws_rs {
public static void main(String[] args) {
           
           ClientConfig config = new ClientConfig();
           Client client = ClientBuilder. newClient(config);
           
//         URI uri = UriBuilder.fromUri("http://localhost:8080/rest.jersey/first/c2fservice").build();
           URI uri = UriBuilder.fromUri("http://localhost:8080/rest.jersey/first/c2fservice/95").build();
           WebTarget target = client.target( uri);
           
           String response = target.request().accept(MediaType. TEXT_PLAIN).get(Response. class).toString();
           
           String xmlAnswer = target.request().accept(MediaType. APPLICATION_XML).get(String.class );
           String textXmlAnswer = target.request().accept(MediaType. TEXT_XML).get(String. class);
           
           System. out.println( "Response: "+ response);
           System. out.println( "application/Xml: "+xmlAnswer );
           System. out.println( "text/xml: "+ textXmlAnswer);
     }

}


也可使用java.net.connection來建立客戶端測試,以下:json

5.client.CFClient_java_net_connection.java:
api

package client;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class CFClient_java_net_connection {
     public static void main(String[] args) {
          System. out.println( getContent("http://localhost:8080/rest.jersey/first/c2fservice"));
          System. out.println( getContent("http://localhost:8080/rest.jersey/first/c2fservice/98"));
          System. out.println( getContent("http://localhost:8080/rest.jersey/first/f2cservice"));
          System. out.println( getContent("http://localhost:8080/rest.jersey/first/f2cservice/98"));
     }

     private static String getContent(String myURL) {

           System. out.println( "Requested URL: " + myURL );
           StringBuilder sb = new StringBuilder();
           HttpURLConnection urlConn = null;
           InputStreamReader in = null;

           URL url;
            try {
                 url = new URL( myURL);
                 urlConn = (HttpURLConnection)url.openConnection();
                 urlConn.setReadTimeout(600 * 1000);
                 urlConn.setRequestMethod( "GET");
                 if ( urlConn != null && urlConn.getInputStream() != null) {
                      in = new InputStreamReader(urlConn.getInputStream(),"utf-8" );
                     BufferedReader br = new BufferedReader(in);
                     String line;
                      while (( line = br.readLine()) != null) {
                            sb.append( line);
                     }
                      br.close();
                }
                 in.close();
           } catch (Exception e) {
                 e.printStackTrace();
                 throw new RuntimeException( "獲取請求地址出錯" + myURL);
           }

            return sb.toString();
     }
}
相關文章
相關標籤/搜索