restful服务端及客户端开发.doc

上传人:scccc 文档编号:12268375 上传时间:2021-12-02 格式:DOC 页数:24 大小:165KB
返回 下载 相关 举报
restful服务端及客户端开发.doc_第1页
第1页 / 共24页
restful服务端及客户端开发.doc_第2页
第2页 / 共24页
restful服务端及客户端开发.doc_第3页
第3页 / 共24页
亲,该文档总共24页,到这儿已超出免费预览范围,如果喜欢就下载吧!
资源描述

《restful服务端及客户端开发.doc》由会员分享,可在线阅读,更多相关《restful服务端及客户端开发.doc(24页珍藏版)》请在三一文库上搜索。

1、Restful 服务端及客户端调用实例1. 新建 web 工程作为服务端 创建服务端代码前情提示 :GET( SELEC)T :从服务器取出资源(一项或多项)。POST(CREAT)E :在服务器新建一个资源。PUT( UPDAT)E :在服务器更新资源(客户端提供改变后的完整资源)。 PATCH(UPDAT)E :在服务器更新资源(客户端提供改变的属性)。 DELETE(DELETE):从服务器删除资源。2. 服务端代码(每个方法前有注释,包括单参数,多参数, post , get 方式的例子)package com.eviac.blog.restws;import javax.ws.rs.

2、Consumes;import javax.ws.rs.DefaultValue;import javax.ws.rs.FormParam;import javax.ws.rs.GET;import javax.ws.rs.POST;import javax.ws.rs.Path;import javax.ws.rs.PathParam;import javax.ws.rs.Produces;import javax.ws.rs.core.MediaType;import net.sf.json.JSONObject;import com.alibaba.fastjson.JSONArray;

3、* author pavithra*/ 这里 Path定义了类的层次路径。/ 指定了资源类提供服务的 URI 路径。 Path("UserInfoService") public class UserInfo / GET 表示方法会处理 HTTP GET请求GETURI路径。/ 这里 Path定义了类的层次路径。指定了资源类提供服务的 Path("/name/i")/ Produces 定义了资源类方法会生成的媒体类型。 Produces(MediaType.TEXT_XML)/ PathParam 向 Path定义的表达式注入 URI 参数值。 pub

4、lic String userName(PathParam("i")String i) String name = i;return "<User>" + "<Name>" + name + "</Name>" + "</User>"URI路径。URI路径。GET/ 这里 Path定义了类的层次路径。指定了资源类提供服务的 Path("/userinfo/id")/ Produces 定义了资源类方法会生成的媒体类型/Consu

5、mes(MediaType.APPLICATION_JSON) / 传 json Produces(MediaType.APPLICATION_JSON)/ PathParam 向Path定义的表达式注入 URI 参数值。 public String userJson(PathParam("id")String id) /JSONObject jobj=JSONObject.fromObject(id);/id=jobj.getString("id");return ""name":"hanzl",&qu

6、ot;age":1,"id":"+"""+id+"""/ 多参数测试POST/ 这里 Path定义了类的层次路径。指定了资源类提供服务的 Path("/user2info")/ Produces 定义了资源类方法会生成的媒体类型 /Consumes(MediaType.APPLICATION_JSON) / 传 json/ 多参数配置Consumes( MediaType.MULTIPART_FORM_DATA,MediaType.APPLICATION_FORM_ URLE

7、NCODED)Produces(MediaType.APPLICATION_JSON) / 返回 json/ PathParam 向 Path定义的表达式注入 URI 参数值。public String user2Json(FormParam("id")String id,FormParam("name") String name) System.out.println(id);System.out.println(name);return ""name":"+"""+name+&qu

8、ot;""+","age":1,"id":"+"""+id+"""/ 多参数测试 参数为 jsonPOST/这里 Path定义了类的层次路径。指定了资源类提供服务的 URI路径。Path("/user3info")/ Produces 定义了资源类方法会生成的媒体类型/Consumes(MediaType.APPLICATION_JSON) / 传 json/ 多参数配置Consumes( MediaType.MULTIPART_FOR

9、M_DATA,MediaType.APPLICATION_FORM_ URLENCODED)Produces(MediaType.APPLICATION_JSON) / 返回 json/ PathParam 向 Path定义的表达式注入 URI 参数值。public String user3Json(FormParam("id")String id) System.out.println(id);return ""name":"hanzl","age":1,"id":"+&q

10、uot;""+id+"""GETPath("/age/j")Produces(MediaType.TEXT_XML)public String userAge(PathParam("j")int j) int age = j;return "<User>" + "<Age>" + age + "</Age>" + "</User>"3. 配 置 服 务 端 web.xml ( r

11、estful 接 口 发 布 地 址 ) 在 web.xml 中加入如下配置<servlet><servlet -name>Jersey REST Service</servlet-name><servlet -class> com.sun.jersey.spi.container.servlet.ServletContainer</servlet -class><init -param><param -name> com.sun.jersey.config.property.packages</para

12、m -name><param -value>com.eviac.blog.restws</param -value></init -param><load -on-startup>1</load -on-startup></servlet><servlet -mapping><servlet -name>Jersey REST Service</servlet-name> <url-pattern>/rest/*</url -pattern></ser

13、vlet -mapping>4. 编写客户端代码4.1 新建 java 工程来进行服务端的第一次调用:package com.eviac.blog.restclient;import javax.ws.rs.core.MediaType;import com.sun.jersey.api.client.Client;import com.sun.jersey.api.client.ClientResponse;import com.sun.jersey.api.client.WebResource;import com.sun.jersey.api.client.config.Clien

14、tConfig;import com.sun.jersey.api.client.config.DefaultClientConfig;/* author pavithra*/public class UserInfoClient public static final String BASE_URI = "RestflService"public static final String PATH_NAME = "/UserInfoService/name/" public static final String PATH_AGE = "/Us

15、erInfoService/age/"public static void main(String args) String name = "Pavithra" int age = 25;ClientConfig config = new DefaultClientConfig();Client client = Client.create(config);WebResource nameResourceWebResource resource = client.resource(BASE_URI);resource.path("rest").

16、path(PATH_NAME +name);System.out.println("Client Response n"+ getClientResponse(nameResource);System.out.println("Response n" + getResponse(nameResource) + "nn");WebResource ageResource = resource.path("rest").path(PATH_AGE + age);System.out.println("Clie

17、nt Response n"+ getClientResponse(ageResource);System.out.println("Response n" + getResponse(ageResource);/* 返回客户端请求。 例如: GET* 返回请求结果状态“ 200 OK”。* param service* return*/private static String getClientResponse(WebResource resource) return resource.accept(MediaType.TEXT_XML).get(Client

18、Response.class) .toString();* 返回请求结果 XML 例如: <User><Name>Pavithra</Name></User> * param service* return*/private static String getResponse(WebResource resource) return resource.accept(MediaType.TEXT_XML).get(String.class);调用结果:4.2get 方式还可以直接从浏览器直接调用浏览器调用:以上这些都是单纯的 get 方式提交的数据

19、可使用5. 客户端调用我这有两种方式HttpURLConnection, HttpClient两种5.1HttpURLConnection 调用restful 接口代码如下:package com.eviac.blog.restclient;,返回结果为 json/* 测试 get 请求方式,请求数据为单个参数* get 方法提交* 返回数据 json*/ import java.io.BufferedInputStream;import java.io.BufferedReader;import java.io.ByteArrayOutputStream;import java.io.IOE

20、xception;import java.io.InputStreamReader;import java.io.PrintWriter;import .HttpURLConnection;import .MalformedURLException;import .URL;public class JavaNetURLRESTFulClient /post 方式public static String postDownloadJson(String path,String post)URL url = null;/ 接口的地址path=""/ 请求的参数post="

21、;id=""id":"11"""try url = new URL(path);(HttpURLConnection)HttpURLConnection httpURLConnectionurl.openConnection();httpURLConnection.setRequestMethod("POST");/ 提交模式 / conn.setConnectTimeout(10000);/ 连接超时 单位毫秒 / conn.setReadTimeout(2000);/ 读取超时 单位毫秒 / 发送 P

22、OST请求必须设置如下两行 httpURLConnection.setDoOutput(true);httpURLConnection.setDoInput(true);/httpURLConnection.setRequestProperty("Content -Type", "application/json;charset=utf -8");/ 获取 URLConnection 对象对应的输出流 PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream()

23、;/ 发送请求参数 printWriter.write(post);/post 的参数 xx=xx&yy=yy / flush 输出流的缓冲printWriter.flush();/ 开始获取数据BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream();ByteArrayOutputStream bos = new ByteArrayOutputStream();int len;byte arr = new byte1024; while(len=bis.read(arr)!

24、= -1) bos.write(arr,0,len);bos.flush();bos.close();return bos.toString("utf -8"); catch (Exception e) e.printStackTrace(); return null; public static void main(String args) try String id="123"String targetURL = "" targetURL+=id;URL restServiceURL = new URL(targetURL);Ht

25、tpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection();httpConnection.setRequestMethod("GET"); / 返回 xml/httpConnection.setRequestProperty("Content -Type", "text/plain; charset=utf -8");/ 返回 json httpConnection.setRequestProperty("Accep

26、t", "application/json");if (httpConnection.getResponseCode() != 200) throw new RuntimeException("HTTP GET Request Failed withError code : "+ httpConnection.getResponseCode();BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(httpConnection.getInputStrea

27、m();String output;System.out.println("Output from Server:n");while (output = responseBuffer.readLine() != null) System.out.println(output);/ 解析 jsonhttpConnection.disconnect(); catch (MalformedURLException e) e.printStackTrace(); catch (IOException e) e.printStackTrace();/ postDownloadJson

28、(null,null);5.2HttpClient 调用 restful 接口( post & get 方式)代码如下:package com.eviac.blog.restclient;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import mons.httpclient.HttpClient;import mons.httpclient.HttpException;import mons.ht

29、tpclient.NameValuePair;import mons.httpclient.methods.GetMethod;import mons.httpclient.methods.PostMethod;public class RestClient public static void main(String args) String urlpost = ""String urlget = ""HttpClient client = new HttpClient();/POST 方法GetMethod getmethod=new GetMeth

30、od(urlget);PostMethod method = new PostMethod(urlpost);NameValuePair data = new NameValuePair("id", ""id":"11""); method.setRequestBody(data);try int statusCode = client.executeMethod(method);if (statusCode = 200) / String strJson = method.getResponseBodyAsStr

31、ing(); / System.out.println("post 方法 ="+strJson);BufferedReader(newBufferedReader reader = newInputStreamReader(method.getResponseBodyAsStream();StringBuffer stringBuffer = new StringBuffer();String str = ""while(str = reader.readLine()!=null) stringBuffer.append(str);String ts =

32、 stringBuffer.toString(); System.out.println("post 方法 ="+ts); catch (HttpException e) e.printStackTrace(); catch (IOException e) e.printStackTrace();/ 执行 get 方法try int statusCode = client.executeMethod(getmethod);if (statusCode = 200) String strJson = getmethod.getResponseBodyAsString(); S

33、ystem.out.println("get 方法 ="+strJson);/ System.out.println(map.get("user").getUsername(); catch (HttpException e) e.printStackTrace(); catch (IOException e) e.printStackTrace();5.3HttpURLConnection 调用 restful 接口( post ,多参数)服务端方法配置:/ 多参数测试POST/ 这里 Path定义了类的层次路径。指定了资源类提供服务的 URI路径。P

34、ath( "/user2info")/ Produces 定义了资源类方法会生成的媒体类型 /Consumes(MediaType.APPLICATION_JSON) / 传json / 多参数配置Consume(s MediaType. MULTIPART_FORM_DAT,MAediaType. APPLICATION_FORM_URLENCODE) DProduces(MediaType. APPLICATION_JSON) / 返回 json / PathParam 向 Path定义的表达式注入 URI参数值。 public String user2Json(For

35、mParam( "id" )Stringid , FormParam( "name" ) Stringname) System. out .println(id );System. out .println(name);return""name":" +""" +name+""" +","age":1,"id":" +""" +id +""&quo

36、t; ;客户端调用:代码package com.eviac.blog.restclient;import java.io.BufferedInputStream;import java.io.BufferedReader;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import .HttpURLConnection;import .MalformedURLException;import .U

37、RL;/* author Hanlong* 多参数配置* 请求数据为为多个参数* 返回结果是 Json* 放在 body 体里* Post 方法提交*/public class Test2paras /post 方式public static String postDownloadJson(String path,String post)URL url = null;path=""post=""id":"11"""String post1="id=1&name=hanzl"tr

38、y url = new URL(path);HttpURLConnection httpURLConnection =(HttpURLConnection) url.openConnection();httpURLConnection.setRequestMethod("POST");/提交模式/ conn.setConnectTimeout(10000);/连接超时 单位毫秒/ conn.setReadTimeout(2000);/读取超时 单位毫秒/发送 POST请求必须设置如下两行httpURLConnection.setDoOutput(true);httpURLC

39、onnection.setDoInput(true);/httpURLConnection.setRequestProperty("Content-Type","application/json; charset=utf-8");/获取 URLConnection 对象对应的输出流PrintWriter printWriter = newPrintWriter(httpURLConnection.getOutputStream();/ 发送请求参数printWriter.write(post1);/post的参数xx=xx&yy=yy/ flus

40、h 输出流的缓冲printWriter.flush();/ 开始获取数据BufferedInputStream bis = newBufferedInputStream(httpURLConnection.getInputStream( );ByteArrayOutputStream bos = newByteArrayOutputStream();int len;byte arr = new byte1024; while(len=bis.read(arr)!= -1) bos.write(arr,0,len); bos.flush();bos.close();return bos.toSt

41、ring("utf-8"); catch (Exception e) e.printStackTrace();return null;public static void main(String args) System.out.println( postDownloadJson(null,null);5.4HttpURLConnection 调用 restful 接口( post ,参数为 json , 返回参数为 json )服务端/ 多参数测试 参数为 jsonPOST/ 这里 Path定义了类的层次路径。指定了资源类提供服务的 URI路径。Path( "/

42、user3info")/ Produces 定义了资源类方法会生成的媒体类型 /Consumes(MediaType.APPLICATION_JSON) / 传json / 多参数配置Consume(s MediaType. MULTIPART_FORM_DAT,MAediaType. A PPLICATION_FORM_URLENCODE) DProduces(MediaType. APPLICATION_JSON) / 返回 json / PathParam 向 Path定义的表达式注入 URI参数值。public String user3Json( FormParam( &qu

43、ot;id" )String id ) System. out .println( id );return""name":"hanzl","age":1,"id":" +""" +id +"""客户端代码package com.eviac.blog.restclient;import java.io.BufferedInputStream;import java.io.BufferedReader;import java.io

44、.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import .HttpURLConnection;import .MalformedURLException;import .URL;/* author Hanlong* 多参数配置* 请求数据 json* 返回结果是 Json* Post 方法提交*/public class TestJsonparams /post 方式public static String postD

45、ownloadJson(String path,String post)URL url = null;path=""post="id="id":"11"""String post1=post;try url = new URL(path);HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();httpURLConnection.setRequestMethod("POST");/ 提交

46、模式/ conn.setConnectTimeout(10000);/ 连接超时 单位毫秒/ conn.setReadTimeout(2000);/ 读取超时 单位毫秒/ 发送 POST请求必须设置如下两行 httpURLConnection.setDoOutput(true); httpURLConnection.setDoInput(true); /httpURLConnection.setRequestProperty("Content -Type","application/json; charset=utf -8");/ 获取 URLConne

47、ction 对象对应的输出流newnewPrintWriter printWriter =PrintWriter(httpURLConnection.getOutputStream();/ 发送请求参数printWriter.write(post1);/post 的参数 xx=xx&yy=yy/ flush 输出流的缓冲 printWriter.flush();/ 开始获取数据BufferedInputStream bis = BufferedInputStream(httpURLConnection.getInputStream();ByteArrayOutputStream bos

48、 = new ByteArrayOutputStream(); int len;byte arr = new byte1024;while(len=bis.read(arr)!= -1) bos.write(arr,0,len); bos.flush();bos.close();return bos.toString("utf -8"); catch (Exception e) e.printStackTrace();return null;public static void main(String args) System.out.println( postDownloadJson(null,null); 6.项目完整包 (附件带 jar 包 )restful 接口客户端&服务端 .rar

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 社会民生


经营许可证编号:宁ICP备18001539号-1