REST例子

与web service类似,REST利用一个更加接近http的协议传递数据。

请求的目的地即是一个URI,数据的格式可以是XML、JSON或者是纯文本。

下面是一个在myeclipse 8.6上的REST小例子,还很不完善先记录下来。

部署REST服务:web service project, 选择了REST的web service

复制代码
 1 package com.test;
 2 
 3 import javax.ws.rs.Consumes;
 4 import javax.ws.rs.GET;
 5 import javax.ws.rs.POST;
 6 import javax.ws.rs.Path;
 7 import javax.ws.rs.PathParam;
 8 import javax.ws.rs.Produces;
 9 import com.sun.jersey.spi.resource.Singleton;
10 
11 @Produces("text/plain")
12 @Path("customers")
13 @Singleton
14 public class Interface {
15 
16     @GET
17     public String getCustomers(){
18         return "getCustomers all";
19     }
20     @GET  
21     @Path("{id}")  
22     public String getCustomer(@PathParam("id") String uid) {  
23         return "your id is "+ uid;  
24     }  
25 }

客户端调用:java project
 1 package com.app;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.IOException;
 5 import java.io.InputStreamReader;
 6 import java.net.HttpURLConnection;
 7 import java.net.MalformedURLException;
 8 import java.net.URL;
 9 
10 public class app {
11 
12     /**
13      * @param args
14 */
15     public static void main(String[] args) throws MalformedURLException {
16         // TODO Auto-generated method stub
17 //实例一个URL资源
18         URL url = null;
19         try {
20             url = new URL("http://localhost:8080/java_ws01/services/customers");
21             //url = new URL("http://localhost:8080/java_ws01/services/customers/321");
22             HttpURLConnection connet;
23             connet = (HttpURLConnection) url.openConnection();
24             if(connet.getResponseCode() != 200){
25                 throw new IOException(connet.getResponseMessage());
26             }
27             //将返回的值存入到String中
28             BufferedReader brd = new BufferedReader(new InputStreamReader(connet.getInputStream()));
29 
30             System.out.println(brd.readLine());
31 
32             connet.disconnect();
33         } catch (IOException e) {
34             // TODO Auto-generated catch block
35             e.printStackTrace();
36         }
37     }
38 }


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部