



版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)
文檔簡介
1、-WORD 格式 - 可編輯 -Restful 服務(wù)端及客戶端調(diào)用實例1. 新建 web 工程作為服務(wù)端 創(chuàng)建服務(wù)端代碼前情提示 :GET ( SELECT):從服務(wù)器取出資源(一項或多項)。POST(CREATE ):在服務(wù)器新建一個資源。PUT( UPDATE ):在服務(wù)器更新資源(客戶端提供改變后的完整資源)。PATCH(UPDATE ):在服務(wù)器更新資源(客戶端提供改變的屬性)。DELETE ( DELETE ):從服務(wù)器刪除資源。2.服務(wù)端代碼(每個方法前有注釋,包括單參數(shù),多參數(shù),post ,get 方式的例子)packagecom.eviac.blog.restws;import
2、javax.ws.rs.Consumes;importjavax.ws.rs.DefaultValue;importjavax.ws.rs.FormParam;importjavax.ws.rs.GET;importjavax.ws.rs.POST;importjavax.ws.rs.Path;importjavax.ws.rs.PathParam;importjavax.ws.rs.Produces;importjavax.ws.rs.core.MediaType;importnet.sf.json.JSONObject;-WORD 格式 - 可編輯 -importcom.alibaba.f
3、astjson.JSONArray;/* author pavithra*/ 這里 Path定義了類的層次路徑。/ 指定了資源類提供服務(wù)的 URI 路徑。Path("UserInfoService")public class UserInfo / GET表示方法會處理HTTP GET 請求GET/這里 Path定義了類的層次路徑。指定了資源類提供服務(wù)的URI 路徑。Path("/name/i")/ Produces定義了資源類方法會生成的媒體類型。Produces(MediaType.TEXT_XML)/ PathParam向Path定義的表達式注入UR
4、I 參數(shù)值。public String userName(PathParam("i")String i) String name = i;return "<User>" + "<Name>" + name + "</Name>" + "</User>"-WORD 格式 - 可編輯 -WORD 格式 - 可編輯 -GET/這里 Path定義了類的層次路徑。指定了資源類提供服務(wù)的URI 路徑。Path("/userinfo/id")
5、/ Produces定義了資源類方法會生成的媒體類型/Consumes(MediaType.APPLICATION_JSON) /傳 jsonProduces(MediaType.APPLICATION_JSON)/ PathParam向Path定義的表達式注入URI 參數(shù)值。public String userJson(PathParam("id")String id) /JSONObjectjobj=JSONObject.fromObject(id);/id=jobj.getString("id");return ""name&q
6、uot;:"hanzl","age":1,"id":"+"""+id+"""/ 多參數(shù)測試POST/這里 Path定義了類的層次路徑。指定了資源類提供服務(wù)的URI 路徑。Path("/user2info")/ Produces定義了資源類方法會生成的媒體類型/Consumes(MediaType.APPLICATION_JSON) /傳 json-WORD 格式 - 可編輯 -/ 多參數(shù)配置-WORD 格式 - 可編輯 -Consumes( Me
7、diaType.MULTIPART_FORM_DATA,MediaType.APPLICATION_FORM_URLENCODED)Produces(MediaType.APPLICATION_JSON) /返回 json/ PathParam向Path定義的表達式注入URI 參數(shù)值。public String user2Json(FormParam("id")String id,FormParam("name") String name) System.out.println(id);System.out.println(name);return&qu
8、ot;"name":"+"""+name+"""+","age":1,"id":"+"""+id+"""/ 多參數(shù)測試參數(shù)為 json POST/這里 Path定義了類的層次路徑。指定了資源類提供服務(wù)的URI 路徑。Path("/user3info")/ Produces定義了資源類方法會生成的媒體類型/Consumes(MediaType.APPLICATION_J
9、SON) /傳 json/ 多參數(shù)配置Consumes( MediaType.MULTIPART_FORM_DATA,MediaType.APPLICATION_FORM_URLENCODED)Produces(MediaType.APPLICATION_JSON) /返回 json/ PathParam向Path定義的表達式注入URI 參數(shù)值。-WORD 格式 - 可編輯 -public String user3Json(FormParam("id")-WORD 格式 - 可編輯 -String id) System.out.println(id);return &quo
10、t;"name":"hanzl","age":1,"id":"+"""+id+"""GETPath("/age/j")Produces(MediaType.TEXT_XML)public String userAge(PathParam("j")int j) int age = j;return "<User>" + "<Age>" + age
11、 + "</Age>" + "</User>"3. 配 置 服 務(wù) 端web.xml( restful接 口 發(fā) 布 地 址 ) 在web.xml中加入如下配置<servlet><servlet-name>Jersey REST Service</servlet-name><servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class><init-param>
12、;<param-name>perty.packages</param-name>-WORD 格式 - 可編輯 -<param-value>com.eviac.blog.restws</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping>-WORD 格式 - 可編輯 -<servlet-name>Jerse
13、y REST Service</servlet-name><url-pattern>/rest/*</url-pattern></servlet-mapping>4.編寫客戶端代碼4.1 新建 java 工程來進行服務(wù)端的第一次調(diào)用:packagecom.eviac.blog.restclient;importjavax.ws.rs.core.MediaType;importcom.sun.jersey.api.client.Client;importcom.sun.jersey.api.client.ClientResponse;importc
14、om.sun.jersey.api.client.WebResource;importcom.sun.jersey.api.client.config.ClientConfig;importcom.sun.jersey.api.client.config.DefaultClientConfig;/* author pavithra*/public class UserInfoClient public static final String BASE_URI = "http:/localhost:8080/RestflService" public static final
15、 String PATH_NAME = "/UserInfoService/name/" public static finalString PATH_AGE = "/UserInfoService/age/"public static void main(String args) String name = "Pavithra"int age = 25;-WORD 格式 - 可編輯 -ClientConfigconfig = new DefaultClientConfig();Client client = Client.creat
16、e(config);WebResource resource = client.resource(BASE_URI);WebResourcenameResource = resource.path("rest").path(PATH_NAME + name); System.out.println("Client Response n"+ getClientResponse(nameResource); System.out.println("Response n" + getResponse(nameResource) + &quo
17、t;nn");-WORD 格式 - 可編輯 -WebResourceageResource = resource.path("rest").path(PATH_AGE + age); System.out.println("Client Response n"+ getClientResponse(ageResource); System.out.println("Response n" + getResponse(ageResource);/* 返回客戶端請求。例如: GET* http:/localhost:8080/R
18、ESTfulWS/rest/UserInfoService/name/Pavithra* 返回請求結(jié)果狀態(tài)“200 OK”。* param service* return*/private static String getClientResponse(WebResource resource) returnresource.accept(MediaType.TEXT_XML).get(ClientResponse.class).toString();/* 返回請求結(jié)果XML 例如: <User><Name>Pavithra</Name></User&
19、gt;* param service* return*/private static String getResponse(WebResource resource) returnresource.accept(MediaType.TEXT_XML).get(String. class);調(diào)用結(jié)果:-WORD 格式 - 可編輯 -4.2get方式還可以直接從瀏覽器直接調(diào)用瀏覽器調(diào)用:以上這些都是單純的get 方式提交的數(shù)據(jù)可使用-WORD 格式 - 可編輯 -5.客戶端調(diào)用我這有兩種方式HttpURLConnection,HttpClient兩種5.1HttpURLConnection 調(diào)用
20、restful 接口代碼如下:packagecom.eviac.blog.restclient;/* 測試 get 請求方式,請求數(shù)據(jù)為單個參數(shù),返回結(jié)果為json* get 方法提交* 返回數(shù)據(jù) json*/importjava.io.BufferedInputStream;importjava.io.BufferedReader;importjava.io.ByteArrayOutputStream;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.PrintWriter;.HttpURLConn
21、ection;.MalformedURLException;import .URL;public class JavaNetURLRESTFulClient /post方式public static String postDownloadJson(String path,Stringpost) URL url = null;/ 接口的地址path="http:/localhost:8080/RestflService/rest/UserInfoService/userinfo"/ 請求的參數(shù)post="id=""id":"1
22、1"""try url = new URL(path);-WORD 格式 - 可編輯 -HttpURLConnectionhttpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("POST");/提交模式/ conn.setConnectTimeout(10000);/ 連接超時單位毫秒/ conn.setReadTimeout(2000);/讀取超時單位毫秒/ 發(fā)送 POST 請求必須設(shè)置如下兩行httpU
23、RLConnection.setDoOutput(true);httpURLConnection.setDoInput(true);/httpURLConnection.setRequestProperty("Content-Type", "application/json;-WORD 格式 - 可編輯 -charset=utf-8");/ 獲取 URLConnection 對象對應(yīng)的輸出流PrintWriterprintWriter = new PrintWriter(httpURLConnection.getOutputStream();/ 發(fā)送請求
24、參數(shù)printWriter.write(post);/post的參數(shù) xx=xx&yy=yy/ flush 輸出流的緩沖printWriter.flush();/ 開始獲取數(shù)據(jù)BufferedInputStreambis = newBufferedInputStream(httpURLConnection.getInputStream();ByteArrayOutputStreambos = new ByteArrayOutputStream();intlen;byte arr = new byte1024;while(len=bis.read(arr)!= -1)bos.write(
25、arr,0,len);bos.flush();bos.close();returnbos.toString("utf-8"); catch (Exception e) e.printStackTrace();return null;public static void main(String args) try String id="123"String targetURL ="http:/localhost:8080/RestflService/rest/UserInfoService/userinfo/"targetURL+=id
26、;URL restServiceURL = new URL(targetURL);HttpURLConnectionhttpConnection = (HttpURLConnection) restServiceURL.openConnection(); httpConnection.setRequestMethod("GET");-WORD 格式 - 可編輯 -/返回 xml/httpConnection.setRequestProperty("Content-Type", "text/plain;charset=utf-8");/
27、 返回 jsonhttpConnection.setRequestProperty("Accept", "application/json");if (httpConnection.getResponseCode() != 200) throw new RuntimeException("HTTP GET Request Failed with Error code : "+ httpConnection.getResponseCode();-WORD 格式 - 可編輯 -BufferedReaderresponseBuffer =
28、new BufferedReader(newInputStreamReader( (httpConnection.getInputStream();String output;System.out.println("Output from Server:n");while (output = responseBuffer.readLine() != null) System.out.println(output);/ 解析 jsonhttpConnection.disconnect(); catch (MalformedURLException e) e.printStac
29、kTrace(); catch (IOException e) e.printStackTrace();/ postDownloadJson(null,null);5.2HttpClient 調(diào)用 restful 接口( post & get 方式)代碼如下:packagecom.eviac.blog.restclient;importjava.io.BufferedReader;-WORD 格式 - 可編輯 -importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;mons
30、.httpclient.HttpClient;mons.httpclient.HttpException;mons.httpclient.NameValuePair;mons.httpclient.methods.GetMethod;mons.httpclient.methods.PostMethod;-WORD 格式 - 可編輯 -public class RestClient public static void main(String args) String urlpost ="http:/localhost:8080/RestflService/rest/UserInfoS
31、ervice/user3info" Stringurlget = "http:/localhost:8080/RestflService/rest/UserInfoService/name/1"HttpClient client = new HttpClient();/POST 方法GetMethodgetmethod=new GetMethod(urlget);PostMethod method = new PostMethod(urlpost);NameValuePair data = newNameValuePair("id", &quo
32、t;"id":"11"");method.setRequestBody(data);try intstatusCode = client.executeMethod(method);if (statusCode = 200) / String strJson = method.getResponseBodyAsString();/ System.out.println("post 方法 ="+strJson);BufferedReader reader = new BufferedReader(newInputStreamR
33、eader(method.getResponseBodyAsStream();StringBufferstringBuffer = new StringBuffer();String str = ""while(str = reader.readLine()!=null)stringBuffer.append(str);String ts = stringBuffer.toString();System.out.println("post方法 ="+ts); catch (HttpExceptione) e.printStackTrace(); catc
34、h (IOExceptione) e.printStackTrace();-WORD 格式 - 可編輯 -/ 執(zhí)行 get 方法try intstatusCode = client.executeMethod(getmethod);if (statusCode = 200) String strJson =getmethod.getResponseBodyAsString(); System.out.println("get方法="+strJson);/ System.out.println(map.get("user").getUsername();-
35、WORD 格式 - 可編輯 - catch (HttpExceptione) e.printStackTrace(); catch (IOExceptione) e.printStackTrace();5.3HttpURLConnection 調(diào)用 restful 接口( post,多參數(shù))服務(wù)端方法配置:/ 多參數(shù)測試POST/這里 Path定義了類的層次路徑。指定了資源類提供服務(wù)的URI路徑。Path( "/user2info")/Produces 定義了資源類方法會生成的媒體類型/Consumes(MediaType.APPLICATION_JSON) /傳 json/ 多參數(shù)配置Consumes( MediaType.MULTIPART_FORM_DATA,Med
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- AI助理醫(yī)學(xué)人才培養(yǎng)的策略及實施路徑
- 2025簡易建筑材料運輸車合同
- 2025企業(yè)員工勞動合同范本
- 部編版語文八年級下冊 被壓扁的沙子教案
- 特種設(shè)備監(jiān)管b證考試試題及答案
- 2025企業(yè)辦公租賃合同樣本參考
- 2025企業(yè)團建活動服務(wù)合同
- 一級c計算機考試試題及答案
- 諸暨教師面試題庫及答案
- 廣西幼師學(xué)前專業(yè)兒童文學(xué):小烏龜放風箏簡案
- 我的家鄉(xiāng)唐山
- 【MOOC】《概率論與數(shù)理統(tǒng)計》(電子科技大學(xué))中國大學(xué)慕課MOOC答案
- 醫(yī)療質(zhì)控員培訓(xùn)
- 讀書筆記:明冬亮《系統(tǒng)之美:決策者的系統(tǒng)思考》
- T-GDJD 002-2024 電茶壺電水壺專用耦合器
- 數(shù)字經(jīng)濟與產(chǎn)業(yè)鏈創(chuàng)新
- 醫(yī)院培訓(xùn)課件:《醫(yī)院感染管理制度與職責》
- 【MOOC】實境英語聽說-河南大學(xué) 中國大學(xué)慕課MOOC答案
- 問卷調(diào)查設(shè)計及研究方法(浙江大學(xué))知到智慧樹章節(jié)答案
- 《冰川地貌》課件
- 果園管理合同
評論
0/150
提交評論