restful服务端及客户端开发.docx
《restful服务端及客户端开发.docx》由会员分享,可在线阅读,更多相关《restful服务端及客户端开发.docx(43页珍藏版)》请在冰豆网上搜索。
![restful服务端及客户端开发.docx](https://file1.bdocx.com/fileroot1/2022-12/7/1852ad6e-2638-462c-9e77-64cb46ca9163/1852ad6e-2638-462c-9e77-64cb46ca91631.gif)
restful服务端及客户端开发
Restful服务端及客户端调用实例
1.新建web工程作为服务端创建服务端代码
前情提示:
GET(SELECT):
从服务器取出资源(一项或多项)。
POST(CREATE):
在服务器新建一个资源。
PUT(UPDATE):
在服务器更新资源(客户端提供改变后的完整资源)。
PATCH(UPDATE):
在服务器更新资源(客户端提供改变的属性)。
DELETE(DELETE):
从服务器删除资源。
2.服务端代码(每个方法前有注释,包括单参数,多参数,
post,get方式的例子)
packagecom.eviac.blog.restws;
importjavax.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;
/**
*
*@authorpavithra
*
*/
//这里@Path定义了类的层次路径。
//指定了资源类提供服务的URI路径。
@Path("UserInfoService")
publicclassUserInfo{
//@GET表示方法会处理HTTPGET请求
@GET
//这里@Path定义了类的层次路径。
指定了资源类提供服务的URI路径。
@Path("/name/{i}")
//@Produces定义了资源类方法会生成的媒体类型。
@Produces(MediaType.TEXT_XML)
//@PathParam向@Path定义的表达式注入URI参数值。
publicStringuserName(@PathParam("i")
Stringi){
Stringname=i;
return""+""+name+""+"";
}
@GET
//这里@Path定义了类的层次路径。
指定了资源类提供服务的URI路径。
@Path("/userinfo/{id}")
//@Produces定义了资源类方法会生成的媒体类型
//@Consumes(MediaType.APPLICATION_JSON)//传json
@Produces(MediaType.APPLICATION_JSON)
//@PathParam向@Path定义的表达式注入URI参数值。
publicStringuserJson(@PathParam("id")
Stringid){
//JSONObjectjobj=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参数值。
publicStringuser2Json(@FormParam("id")
Stringid,@FormParam("name")Stringname){
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参数值。
publicStringuser3Json(@FormParam("id")
Stringid){
System.out.println(id);
return"{\"name\":
\"hanzl\",\"age\":
1,\"id\":
"+"\""+id+"\"}";
}
@GET
@Path("/age/{j}")
@Produces(MediaType.TEXT_XML)
publicStringuserAge(@PathParam("j")
intj){
intage=j;
return""+""+age+""+"";
}
}
3.配置服务端web.xml(restful接口发布地址)在
web.xml中加入如下配置
JerseyRESTService
com.sun.jersey.spi.container.servlet.ServletContainer
com.sun.jersey.config.property.packages
com.eviac.blog.restws
1
JerseyRESTService
/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.sun.jersey.api.client.WebResource;
importcom.sun.jersey.api.client.config.ClientConfig;
importcom.sun.jersey.api.client.config.DefaultClientConfig;
/**
*
*@authorpavithra
*
*/
publicclassUserInfoClient{
publicstaticfinalStringBASE_URI="http:
//localhost:
8080/RestflService";publicstaticfinalStringPATH_NAME="/UserInfoService/name/";publicstaticfinalStringPATH_AGE="/UserInfoService/age/";
publicstaticvoidmain(String[]args){
Stringname="Pavithra";
intage=25;
ClientConfigconfig=newDefaultClientConfig();
Clientclient=Client.create(config);
WebResourceresource=client.resource(BASE_URI);
WebResourcenameResource=resource.path("rest").path(PATH_NAME+name);System.out.println("ClientResponse\n"
+getClientResponse(nameResource));System.out.println("Response\n"+getResponse(nameResource)+"\n\n");
WebResourceageResource=resource.path("rest").path(PATH_AGE+age);System.out.println("ClientResponse\n"
+getClientResponse(ageResource));System.out.println("Response\n"+getResponse(ageResource));
}
/**
*返回客户端请求。
例如:
GET
*http:
//localhost:
8080/RESTfulWS/rest/UserInfoService/name/Pavithra
*返回请求结果状态“200OK”。
*
*@paramservice
*@return
*/
privatestaticStringgetClientResponse(WebResourceresource){returnresource.accept(MediaType.TEXT_XML).get(ClientResponse.class)
.toString();
}
/**
*返回请求结果XML例如:
Pavithra
*
*@paramservice
*@return
*/
privatestaticStringgetResponse(WebResourceresource){returnresource.accept(MediaType.TEXT_XML).get(String.class);
}
}
调用结果:
4.2get方式还可以直接从浏览器直接调用
浏览器调用:
以上这些都是单纯的get方式提交的数据可使用
5.客户端调用我这有两种方式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;
importjava.io.InputStreamReader;
importjava.io.PrintWriter;
.HttpURLConnection;
.MalformedURLException;
import.URL;
publicclassJavaNetURLRESTFulClient{
//post方式
publicstaticStringpostDownloadJson(Stringpath,Stringpost){URLurl=null;
//接口的地址path="http:
//localhost:
8080/RestflService/rest/UserInfoService/userinfo";
//请求的参数
post="id=\"{\"id\":
\"11\"}\"";
try{
url=newURL(path);
HttpURLConnectionhttpURLConnection=(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对象对应的输出流
PrintWriterprintWriter=newPrintWriter(httpURLConnection.getOutputStream());
//发送请求参数
printWriter.write(post);//post的参数xx=xx&yy=yy
//flush输出流的缓冲
printWriter.flush();
//开始获取数据
BufferedInputStreambis=newBufferedInputStream(httpURLConnection.getInputStream());ByteArrayOutputStreambos=newByteArrayOutputStream();
intlen;
byte[]arr=newbyte[1024];
while((len=bis.read(arr))!
=-1){
bos.write(arr,0,len);
bos.flush();
}
bos.close();
returnbos.toString("utf-8");
}catch(Exceptione){e.printStackTrace();
}
returnnull;
}
publicstaticvoidmain(String[]args){
try{
Stringid="123";
StringtargetURL="http:
//localhost:
8080/RestflService/rest/UserInfoService/userinfo/";targetURL+=id;
URLrestServiceURL=newURL(targetURL);
HttpURLConnectionhttpConnection=(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){
thrownewRuntimeException("HTTPGETRequestFailedwithErrorcode:
"
+httpConnection.getResponseCode());
}
BufferedReaderresponseBuffer=newBufferedReader(newInputStreamReader((httpConnection.getInputStream())));
Stringoutput;
System.out.println("OutputfromServer:
\n");
while((output=responseBuffer.readLine())!
=null){
System.out.println(output);
}
//解析json
httpConnection.disconnect();
}catch(MalformedURLExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
}
//postDownloadJson(null,null);
}
5.2HttpClient调用restful接口(post&get方式)
代码如下:
packagecom.eviac.blog.restclient;
importjava.io.BufferedReader;
importjava.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;
publicclassRestClient{
publicstaticvoidmain(String[]args){
Stringurlpost="http:
//localhost:
8080/RestflService/rest/UserInfoService/user3info";Stringurlget="http:
//localhost:
8080/RestflService/rest/UserInfoService/name/1";
HttpClientclient=newHttpClient();
//POST方法
GetMethodgetmethod=newGetMethod(urlget);
PostMethodmethod=newPostMethod(urlpost);
NameValuePair[]data={
newNameValuePair("id","{\"id\":
\"11\"}")};
method.setRequestBody(data);
try{
intstatusCode=client.executeMethod(method);
if(statusCode==200){
//StringstrJson=method.getResponseBodyAsString();
//System.out.println("post方法="+strJson);
BufferedReaderreader=newBufferedReader(newInputStreamReader(method.getResponseBodyAsStream()));
StringBufferstringBuffer=newStringBuffer();
Stringstr="";
while((str=reader.readLine())!
=null){
stringBuffer.append(str);
}
Stringts=stringBuffer.toString();
System.out.println("post方法="+ts);
}
}catch(Http