restful服务端及客户端开发Word格式.docx
- 文档编号:17655683
- 上传时间:2022-12-07
- 格式:DOCX
- 页数:43
- 大小:80.13KB
restful服务端及客户端开发Word格式.docx
《restful服务端及客户端开发Word格式.docx》由会员分享,可在线阅读,更多相关《restful服务端及客户端开发Word格式.docx(43页珍藏版)》请在冰豆网上搜索。
*
*/
//这里@Path定义了类的层次路径。
//指定了资源类提供服务的URI路径。
@Path("
UserInfoService"
)
publicclassUserInfo{
//@GET表示方法会处理HTTPGET请求
@GET
指定了资源类提供服务的URI路径。
/name/{i}"
//@Produces定义了资源类方法会生成的媒体类型。
@Produces(MediaType.TEXT_XML)
//@PathParam向@Path定义的表达式注入URI参数值。
publicStringuserName(@PathParam("
i"
Stringi){
Stringname=i;
return"
<
User>
"
+"
Name>
+name+"
/Name>
/User>
;
}
/userinfo/{id}"
//@Produces定义了资源类方法会生成的媒体类型
//@Consumes(MediaType.APPLICATION_JSON)//传json
@Produces(MediaType.APPLICATION_JSON)
publicStringuserJson(@PathParam("
id"
Stringid){
//JSONObjectjobj=JSONObject.fromObject(id);
//id=jobj.getString("
);
{\"
name\"
:
\"
hanzl\"
\"
age\"
1,\"
id\"
+"
+id+"
}"
//多参数测试
@POST
/user2info"
//多参数配置
@Consumes({MediaType.MULTIPART_FORM_DATA,MediaType.APPLICATION_FORM_URLENCODED})
@Produces(MediaType.APPLICATION_JSON)//返回json
publicStringuser2Json(@FormParam("
Stringid,@FormParam("
name"
)Stringname){
System.out.println(id);
System.out.println(name);
return
+name+"
//多参数测试参数为json
/user3info"
publicStringuser3Json(@FormParam("
/age/{j}"
publicStringuserAge(@PathParam("
j"
intj){
intage=j;
Age>
+age+"
/Age>
3.配置服务端web.xml(restful接口发布地址)在
web.xml中加入如下配置
servlet>
servlet-name>
JerseyRESTService<
/servlet-name>
servlet-class>
com.sun.jersey.spi.container.servlet.ServletContainer
/servlet-class>
init-param>
param-name>
com.sun.jersey.config.property.packages
/param-name>
param-value>
com.eviac.blog.restws<
/param-value>
/init-param>
load-on-startup>
1<
/load-on-startup>
/servlet>
servlet-mapping>
url-pattern>
/rest/*<
/url-pattern>
/servlet-mapping>
4.编写客户端代码
4.1新建java工程
来进行服务端的第一次调用:
packagecom.eviac.blog.restclient;
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;
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));
Response\n"
+getResponse(nameResource)+"
\n\n"
WebResourceageResource=resource.path("
).path(PATH_AGE+age);
+getClientResponse(ageResource));
+getResponse(ageResource));
*返回客户端请求。
例如:
GET
*http:
8080/RESTfulWS/rest/UserInfoService/name/Pavithra
*返回请求结果状态“200OK”。
*@paramservice
*@return
privatestaticStringgetClientResponse(WebResourceresource){returnresource.accept(MediaType.TEXT_XML).get(ClientResponse.class)
.toString();
*返回请求结果XML例如:
<
Pavithra<
privatestaticStringgetResponse(WebResourceresource){returnresource.accept(MediaType.TEXT_XML).get(String.class);
调用结果:
4.2get方式还可以直接从浏览器直接调用
浏览器调用:
以上这些都是单纯的get方式提交的数据可使用
5.客户端调用我这有两种方式HttpURLConnection,HttpClient
两种
5.1HttpURLConnection调用restful接口
代码如下:
/****
*测试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="
8080/RestflService/rest/UserInfoService/userinfo"
//请求的参数
post="
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;
Stringid="
123"
StringtargetURL="
8080/RestflService/rest/UserInfoService/userinfo/"
targetURL+=id;
URLrestServiceURL=newURL(targetURL);
HttpURLConnectionhttpConnection=(HttpURLConnection)restServiceURL.openConnection();
httpConnection.setRequestMethod("
GET"
//返回xml
//httpConnection.setRequestProperty("
text/plain;
//返回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){
//postDownloadJson(null,null);
5.2HttpClient调用restful接口(post&
get方式)
importjava.io.InputStream;
mons.httpclient.HttpClient;
mons.httpclient.HttpException;
mons.httpclient.NameValuePair;
mons.httpclient.methods.GetMethod;
mons.httpclient.methods.PostMethod;
publicclassRestClient{
Stringurlpost="
8080/RestflService/rest/UserInfoService/user3info"
Stringurlget="
8080/RestflService/rest/UserInfoService/name/1"
HttpClientclient=newHttpClient();
//POST方法
GetMethodgetmethod=newGetMethod(urlget);
PostMethodmethod=newPostMethod(urlpost);
NameValuePair[]data={
newNameValuePair("
)};
method.setRequestBody(data);
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();
+ts);
}catch(Http
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- restful 服务端 客户端 开发