ImageVerifierCode 换一换
格式:DOCX , 页数:43 ,大小:80.13KB ,
资源ID:4718911      下载积分:3 金币
快捷下载
登录下载
邮箱/手机:
温馨提示:
快捷下载时,用户名和密码都是您填写的邮箱或者手机号,方便查询和重复下载(系统自动生成)。 如填写123,账号就是123,密码也是123。
特别说明:
请自助下载,系统不会自动发送文件的哦; 如果您已付费,想二次下载,请登录后访问:我的下载记录
支付方式: 支付宝    微信支付   
验证码:   换一换

加入VIP,免费下载
 

温馨提示:由于个人手机设置不同,如果发现不能下载,请复制以下地址【https://www.bdocx.com/down/4718911.html】到电脑端继续下载(重复下载不扣费)。

已注册用户请登录:
账号:
密码:
验证码:   换一换
  忘记密码?
三方登录: 微信登录   QQ登录  

下载须知

1: 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。
2: 试题试卷类文档,如果标题没有明确说明有答案则都视为没有答案,请知晓。
3: 文件的所有权益归上传用户所有。
4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
5. 本站仅提供交流平台,并不能对任何下载内容负责。
6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

版权提示 | 免责声明

本文(restful服务端及客户端开发.docx)为本站会员(b****5)主动上传,冰豆网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。 若此文所含内容侵犯了您的版权或隐私,请立即通知冰豆网(发送邮件至service@bdocx.com或直接QQ联系客服),我们立即给予删除!

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

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

2、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;importcom.alibaba.fastjson.JSONArray;/* a

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

4、i)String i) String name = i;return + + name + + ;GET/ 这里 Path定义了类的层次路径。指定了资源类提供服务的URI 路径。Path(/userinfo/id)/ Produces 定义了资源类方法会生成的媒体类型/Consumes(MediaType.APPLICATION_JSON) / 传 jsonProduces(MediaType.APPLICATION_JSON)/ PathParam 向Path定义的表达式注入 URI 参数值。public String userJson(PathParam(id)String id) /JS

5、ONObjectjobj=JSONObject.fromObject(id);/id=jobj.getString(id);return name:hanzl,age:1,id:+id+;/ 多参数测试POST/ 这里 Path定义了类的层次路径。指定了资源类提供服务的URI 路径。Path(/user2info)/ Produces 定义了资源类方法会生成的媒体类型/Consumes(MediaType.APPLICATION_JSON) / 传 json/ 多参数配置Consumes( MediaType.MULTIPART_FORM_DATA,MediaType.APPLICATION_

6、FORM_ URLENCODED)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);returnname:+name+,age:1,id:+id+;/ 多参数测试参数为 jsonPOST/ 这里 Path定义了类的层次路径。指定了资源类提供服

7、务的URI 路径。Path(/user3info)/ Produces 定义了资源类方法会生成的媒体类型/Consumes(MediaType.APPLICATION_JSON) / 传 json/ 多参数配置Consumes( MediaType.MULTIPART_FORM_DATA,MediaType.APPLICATION_FORM_ URLENCODED)Produces(MediaType.APPLICATION_JSON) / 返回 json/ PathParam 向Path定义的表达式注入 URI 参数值。public String user3Json(FormParam(id

8、)String id) System.out.println(id);return name:hanzl,age:1,id:+id+;GETPath(/age/j)Produces(MediaType.TEXT_XML)public String userAge(PathParam(j)int j) int age = j;return + + age + + ;3. 配 置 服 务 端 web.xml ( restful 接 口 发 布 地 址 ) 在web.xml 中加入如下配置Jersey REST Servicecom.sun.jersey.spi.container.servlet.

9、ServletContainercom.sun.jersey.config.property.packagescom.eviac.blog.restws1Jersey REST Service/rest/*4.编写客户端代码4.1 新建 java 工程来进行服务端的第一次调用:packagecom.eviac.blog.restclient;importjavax.ws.rs.core.MediaType;importcom.sun.jersey.api.client.Client;importcom.sun.jersey.api.client.ClientResponse;importcom

10、.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 String PAT

11、H_NAME = /UserInfoService/name/; public static final String PATH_AGE = /UserInfoService/age/;public static void main(String args) String name = Pavithra;int age = 25;ClientConfigconfig = new DefaultClientConfig();Client client = Client.create(config);WebResource resource = client.resource(BASE_URI);

12、WebResourcenameResource = resource.path(rest).path(PATH_NAME + name); System.out.println(Client Response n+ getClientResponse(nameResource); System.out.println(Response n + getResponse(nameResource) + nn);WebResourceageResource = resource.path(rest).path(PATH_AGE + age); System.out.println(Client Re

13、sponse n+ getClientResponse(ageResource); System.out.println(Response n + getResponse(ageResource);/* 返回客户端请求。例如: GET* http:/localhost:8080/RESTfulWS/rest/UserInfoService/name/Pavithra* 返回请求结果状态“ 200 OK”。* param service* return*/private static String getClientResponse(WebResource resource) returnres

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

15、端调用我这有两种方式 HttpURLConnection,HttpClient两种5.1HttpURLConnection调用 restful 接口代码如下:packagecom.eviac.blog.restclient;/* 测试 get 请求方式,请求数据为单个参数 ,返回结果为 json* get 方法提交* 返回数据 json*/importjava.io.BufferedInputStream;importjava.io.BufferedReader;importjava.io.ByteArrayOutputStream;importjava.io.IOException;impo

16、rtjava.io.InputStreamReader;importjava.io.PrintWriter;.HttpURLConnection;.MalformedURLException;import .URL;public class JavaNetURLRESTFulClient /post 方式public static String postDownloadJson(String path,String post) URL url = null;/ 接口的地址 path=http:/localhost:8080/RestflService/rest/UserInfoService/

17、userinfo;/ 请求的参数post=id=id:11;try url = new URL(path);HttpURLConnectionhttpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod(POST);/ 提交模式/ conn.setConnectTimeout(10000);/ 连接超时单位毫秒/ conn.setReadTimeout(2000);/ 读取超时单位毫秒/ 发送 POST请求必须设置如下两行httpURLConnection.set

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

19、出流的缓冲printWriter.flush();/ 开始获取数据BufferedInputStreambis = new BufferedInputStream(httpURLConnection.getInputStream(); ByteArrayOutputStreambos = new ByteArrayOutputStream();intlen;byte arr = new byte1024;while(len=bis.read(arr)!= -1)bos.write(arr,0,len);bos.flush();bos.close();returnbos.toString(utf

20、-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;URL restServiceURL = new URL(targetURL);HttpURLConnectionhttpConnection = (HttpURLConnec

21、tion) restServiceURL.openConnection(); httpConnection.setRequestMethod(GET);/ 返回 xml/httpConnection.setRequestProperty(Content-Type, text/plain;charset=utf-8);/ 返回 jsonhttpConnection.setRequestProperty(Accept, application/json);if (httpConnection.getResponseCode() != 200) throw new RuntimeException(

22、HTTP GET Request Failed with Error code : + httpConnection.getResponseCode();BufferedReaderresponseBuffer = new BufferedReader(new InputStreamReader( (httpConnection.getInputStream();String output;System.out.println(Output from Server:n);while (output = responseBuffer.readLine() != null) System.out.

23、println(output);/ 解析 jsonhttpConnection.disconnect(); catch (MalformedURLException e) e.printStackTrace(); catch (IOException e) e.printStackTrace();/ postDownloadJson(null,null);5.2HttpClient 调用 restful 接口( post & get 方式)代码如下:packagecom.eviac.blog.restclient;importjava.io.BufferedReader;importjava.

24、io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;mons.httpclient.HttpClient;mons.httpclient.HttpException;mons.httpclient.NameValuePair;mons.httpclient.methods.GetMethod;mons.httpclient.methods.PostMethod;public class RestClient public static void main(String args) String url

25、post = http:/localhost:8080/RestflService/rest/UserInfoService/user3info; String urlget = http:/localhost:8080/RestflService/rest/UserInfoService/name/1;HttpClient client = new HttpClient();/POST 方法GetMethodgetmethod=new GetMethod(urlget);PostMethod method = new PostMethod(urlpost);NameValuePair dat

26、a = newNameValuePair(id, 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(new InputStreamReader(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 (Http

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1