REST例子

Posted on 2012-03-03 21:07  Fredric  阅读(17777)  评论(2编辑  收藏  举报

REST的例子

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

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

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

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

View Code
 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
View Code
 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 }

Copyright © 2024 Fredric
Powered by .NET 8.0 on Kubernetes