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