REST例子


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 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM