




已阅读5页,还剩15页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Restful服务端及客户端调用实例1. 新建web工程作为服务端创建服务端代码前情提示:GET(SELECT):从服务器取出资源(一项或多项)。POST(CREATE):在服务器新建一个资源。PUT(UPDATE):在服务器更新资源(客户端提供改变后的完整资源)。PATCH(UPDATE):在服务器更新资源(客户端提供改变的属性)。DELETE(DELETE):从服务器删除资源。2.服务端代码(每个方法前有注释,包括单参数,多参数,post,get方式的例子)package com.eviac.blog.restws; import javax.ws.rs.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;/* * * author 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(i) String i) String name = i; return + + name + + ; GET / 这里Path定义了类的层次路径。指定了资源类提供服务的URI路径。 Path(/userinfo/id) / Produces定义了资源类方法会生成的媒体类型 /Consumes(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,age:1,id:+id+; /多参数测试 POST / 这里Path定义了类的层次路径。指定了资源类提供服务的URI路径。 Path(/user2info) / 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 user2Json(FormParam(id) String id,FormParam(name) String name) System.out.println(id); System.out.println(name); return name:+name+,age:1,id:+id+; /多参数测试 参数为json POST / 这里Path定义了类的层次路径。指定了资源类提供服务的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) String id) System.out.println(id); return name:hanzl,age:1,id:+id+; GET Path(/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 Service com.sun.jersey.spi.container.servlet.ServletContainer perty.packages com.eviac.blog.restws 1 Jersey REST Service /rest/* 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.ClientConfig; import com.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 PATH_NAME = /UserInfoService/name/; public static final String PATH_AGE = /UserInfoService/age/; public static void main(String args) String name = Pavithra; int age = 25; ClientConfig config = new DefaultClientConfig(); Client client = Client.create(config); WebResource resource = client.resource(BASE_URI); WebResource nameResource = resource.path(rest).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(Client Response 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) return resource.accept(MediaType.TEXT_XML).get(ClientResponse.class) .toString(); /* * 返回请求结果XML 例如:Pavithra * * param service * return */ private static String getResponse(WebResource resource) return resource.accept(MediaType.TEXT_XML).get(String.class); 调用结果:4.2get方式还可以直接从浏览器直接调用浏览器调用:以上这些都是单纯的get方式提交的数据可使用5.客户端调用我这有两种方式HttpURLConnection, HttpClient两种5.1HttpURLConnection调用restful接口代码如下:package com.eviac.blog.restclient;/* * 测试get请求方式,请求数据为单个参数,返回结果为json * get方法提交 * 返回数据json */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 .URL;public class JavaNetURLRESTFulClient /post方式 public static String postDownloadJson(String path,String post) URL url = null;/接口的地址 path=http:/localhost:8080/RestflService/rest/UserInfoService/userinfo;/请求的参数 post=id=id:11; try url = new URL(path); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod(POST);/ 提交模式 / conn.setConnectTimeout(10000);/连接超时 单位毫秒 / conn.setReadTimeout(2000);/读取超时 单位毫秒 / 发送POST请求必须设置如下两行 httpURLConnection.setDoOutput(true); httpURLConnection.setDoInput(true); /httpURLConnection.setRequestProperty(Content-Type, application/json; charset=utf-8); / 获取URLConnection对象对应的输出流 PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream(); / 发送请求参数 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)!= -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 = http:/localhost:8080/RestflService/rest/UserInfoService/userinfo/; targetURL+=id; URL restServiceURL = new URL(targetURL); HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection(); httpConnection.setRequestMethod(GET); /返回xml /httpConnection.setRequestProperty(Content-Type, text/plain; charset=utf-8); /返回json httpConnection.setRequestProperty(Accept, application/json); if (httpConnection.getResponseCode() != 200) throw new RuntimeException(HTTP GET Request Failed with Error code : + httpConnection.getResponseCode(); BufferedReader responseBuffer = new BufferedReader(new InputStreamReader( (httpConnection.getInputStream(); String output; System.out.println(Output from Server: n); while (output = responseBuffer.readLine() != null) System.out.println(output); /解析json httpConnection.disconnect(); catch (MalformedURLException e) e.printStackTrace(); catch (IOException e) e.printStackTrace(); / postDownloadJson(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.httpclient.NameValuePair;import mons.httpclient.methods.GetMethod;import mons.httpclient.methods.PostMethod;public class RestClient public static void main(String args) String urlpost = http:/localhost:8080/RestflService/rest/UserInfoService/user3info; String urlget = http:/localhost:8080/RestflService/rest/UserInfoService/name/1; HttpClient client = new HttpClient();/POST方法 GetMethod getmethod=new GetMethod(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.getResponseBodyAsString(); / System.out.println(post方法=+strJson); BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(); StringBuffer stringBuffer = new StringBuffer(); String str = ; while(str = reader.readLine()!=null) stringBuffer.append(str); String ts = 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(); System.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路径。 Path(/user2info) / 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 user2Json(FormParam(id) String id,FormParam(name) String name) System.out.println(id); System.out.println(name); return name:+name+,age:1,id:+id+; 客户端调用:代码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 .URL;/* * * author Hanlong * 多参数配置 * 请求数据为为多个参数 * 返回结果是Json * 放在body体里 * Post方法提交 */public class Test2paras /post方式 public static String postDownloadJson(String path,String post) URL url = null; path=http:/localhost:8080/RestflService/rest/UserInfoService/user2info; post=id:11; String post1=id=1&name=hanzl; try url = new URL(path); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod(POST);/ 提交模式 / conn.setConnectTimeout(10000);/连接超时 单位毫秒 / conn.setReadTimeout(2000);/读取超时 单位毫秒 / 发送POST请求必须设置如下两行 httpURLConnection.setDoOutput(true); httpURLConnection.setDoInput(true); /httpURLConnection.setRequestProperty(Content-Type, application/json; charset=utf-8); / 获取URLConnection对象对应的输出流 PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream(); / 发送请求参数 printWriter.write(post1);/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)!= -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); 5.4HttpURLConnection调用restful接口(post,参数为json,返回参数为json)服务端/多参数测试 参数为json POST / 这里Path定义了类的层次路径。指定了资源类提供服务的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) 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.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import .HttpURLConnection;import .MalformedURLException;import .URL;/* * * author Hanlong * 多参数配置 * 请求数据json * 返回
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 徐州线条eps施工方案(3篇)
- 西藏诗词朗诵活动方案策划(3篇)
- 清水泥施工方案(3篇)
- 红色文创活动方案策划(3篇)
- 综合型建筑施工方案(3篇)
- 施工方案验算怎么解决(3篇)
- 北京市昌平区2024-2025学年八年级下学期第一次月考语文考题及答案
- 2025年1-6月我国电子商务发展情况
- 心肺复苏测试题目及答案
- 企业法务合同审查标准化流程及要点清单
- 2024年东南亚一体式直流充电桩市场深度研究及预测报告
- DZ∕T 0213-2020 矿产地质勘查规范 石灰岩、水泥配料类(正式版)
- 学校食堂食材采购询价方案范文(35篇)
- 2023年广西现代物流集团社会招聘、校园招聘考试真题及答案
- 保险公司案件风险排查工作报告
- 《化妆品技术》课件-化妆品的历史起源与发展
- 《建筑施工安全检查标准》JGJ59-20248
- 住宅公共部分装修综合项目施工专项方案
- 安徽医科大学辅导员考试试题2024
- 《合理利用网络作业设计方案-2023-2024学年初中道德与法治统编版》
- JJF1059.1测量不确定度评定培训讲演稿
评论
0/150
提交评论