package cn.itcast.ws3;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.comm ons.httpclient.methods.PostMethod;
/**
* Use URLConnection to call RESTful services
* In addition, it is recommended to use httpClient to read. Quick
* Using urlConnection may not return results
* @author 王健
* @version 1.0 2011-11-18
*/
public class UserRsClient {
UserRsClient() throws Exception{
save2();
all(); div>
}
/**
* Query all information
* @throws Exception
*/
private void all() throws Exception{
GetMethod get = new GetMethod(“http://localhost:9004/users/all”);
get.setRequestHeader (“accept”,”application/json”);
HttpClient hc = new HttpClient(); < /div>
hc.getParams().setContentCharset(“UTF-8”); // Set the encoding
int code = hc.executeMethod(get);
System .err.println(” Status code returned: “+code);
if(code==200){
String str = get.getResponseBodyAsString();
System.err.println(” Return information:
“+str);
}
get.releaseConnection();
}
/**
* To save a message, still use GET method
*/
private void save() throws Exception{
String name = “Jack”;// Because it is a get type, it cannot contain Chinese
String age = “35”;
String url = ” http://localhost:9004/users/save/”+name+”/”+age;
GetMethod get = new GetMethod(url);
get.setRequestHeader(“accept “,”application/json”);
HttpClient hc = new HttpClient();
hc.getParams().setContentCharset(“UTF-8”); // Set encoding
//.setRequestHeader(” Content”,”text/html;charset=UTF-8″);
int code = hc.executeMethod(get);
System.err.println(” Returned status The code is: “+code);
if(code==200){
String str = get.getResponseBodyAsString();
System.err. println(” The information returned is:
“+str);
}
get.releaseConnection();
}
/**
* The following uses POST method
*/
private void save2() throws Exception{
String name = “Wang Jian”;//Because it is a get type, it cannot contain Chinese
String age = “35”;
String url = “http://localhost:9004/users /add/”;
PostMethod pm = new PostMethod(url);
pm.setRequestHeader(“accept”,”application/json”);
pm.setRequestHeader(“Encoding”,”UTF-8″ );
pm.setParameter(“name”,name);
pm.setParameter(“age”,age);
HttpClient hc = new HttpClient ();
hc.getParams().setContentCharset(“UTF-8”);// Set the encoding, otherwise it will return Chinese garbled //TODO: Remember
int code = hc.executeMethod(pm);
System.err.println(“The return value of the Post method is:”+code);
if(code==200){ div>
String ss = pm.getResponseBodyAsString();
System.err.println(“>>:”+ss);
}
pm.releaseConnection();
}
public static void main(String[] args) throws Exception {
new UserRsClient();
Class of CXF publishing service:
l JaxWsServerFactoryBean
•JaxWsServerFactoryBean is used to publish a service, which can be instantiated by default construction.
• Its method is as follows:
•setServiceBean(Object) – Set a service object-*
•setAddress(String url) – bind an address and port-*
•create()-In the JavaSE environment, use jetty to publish WebService.-*
div>
•The following are optional methods:
•setServiceClass(Class cls) – Set the interface class implemented by the service object.
l JaxRsServerFactoryBean
• This type is used to publish RESTful style webService.
• The RESTful style is based on ordinary get and post requests, and can request and respond to json data.
l JaxWsServerFactoryBean
•JaxWsServerFactoryBean is used to publish a service, which can be instantiated by default construction.
• Its method is as follows:
•setServiceBean(Object) – set a service object-*
•setAddress(String url) – bind an address和端口- *
•create() – 在JavaSE环境下,使用jetty发布WebService. – *
•以下是可选方法:
• setServiceClass(Class cls) – 设置服务对象实现的接口类。
l JaxRsServerFactoryBean
•此类用于发布 RESTful风格的webService.
•RESTful 风格是以普通get,post请求为标准的,并可以请求和响应json数据。
4、使用CXF发布一个服务
package cn.leaf.one;
import javax.jws.WebService;
import org.apache.cxf.jaxws.JaxWsServerFactoryBean;
/**
* 使用CXF发布一个服务
* 必须要添加WebService注解。否则不会对外暴露任何一个方法
* @author 王健
*/
@WebService
public class OneService {
public String sayHi(){ ///此方法将会对外公布
return “Good”;
}
public static void main(String[] args) throws Exception {
JaxWsServerFactoryBean bean //使用 jaxWs对其进行发布
= new JaxWsServerFactoryBean();
bean.setServiceBean(new OneService());
bean.setServiceClass(OneService.class);
bean.setAddress(“http://localhost:4444/one”);
bean.create(); //内部使用jetty服务器做为支持
System.err.println(“服务启动成功。。 “);
//Thread.sleep(1000*60*60);
//System.exit(0);
}
}
5、获取上面的wsdl文件: http://localhost:4444/one?wsdl
6、使用wsimport或是wsdl2java生成客户端调用代码,略。
7、发布一个RESTful的webService
package cn.itcast.ws3;
import java.util.ArrayList;
import java.util.List;
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 org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import cn.itcast.domain.User;
/**
* 一个基于JAX-RS的服务
* JAX-RS是无状态的服务
* 注意,必须要在JavaBea n上添加@XMLRootElemet注解
* 此项目启动成功以后,可以通过以下方式访问:
* http://localhost:9004/users?_wadl&_type=xml
* 注意是_wadl&_type=xml
* 将返回一个如何调用RESTful ws的wsdl文件说明书
* @author 王健
* @version 1.0 2011-11-18
*/
@Path(value=”/users/”) //声明uri路径
@Produces(value={MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})//声明支持的类型
public class UserServiceRS {
private List users = new ArrayList();
public UserServiceRS(){
User u = new User();
u.setAge(90);
u.setName(” 大家好”);
users.add(u);
}
/**
* 以下代码,请在地址栏这样访问:
* http://localhost:9004/users/all/
* 即会以XML形式显示所有用户信息
* @return
*/
@GET
@Path(value=”/all/”)
public List getUsers(){
System.err.println(” 调用了users方法”);
return users;
}
/**
* 以下在地址栏输入:
* http://localhost:9004/users/save/Tom/34
* 其中:Tom为要保存的用户名,34为年龄
* 即会保存成功
*/
@GET
@Path(value=”/save/{name}/{age}/”)
public User save(@PathParam(“name”)String name,@PathParam(“age”)String age){
User u = new User();
u.setAge(Integer.parseInt(age));
u.setName(name);
System.err.println(” 保存成功”+u);
users.add(u);
return u;
}
/**
* 提供第二种保存方式
* 使用@FormParam方式设置接收表单的参数
* 通过HttpClient调用,并设置请求参数
*/
@POST
@Path(value=”/add/”)
public User add(@FormParam(“name”)String name,@FormParam(“age”)String age){
User u = new User();
u.setAge(Integer.parseInt(age));
u.setName(name);
System.err.println(” 使用POST保存成功”+u);
users.add(u);
return u;
}
public static void main(String[] args) {
JAXRSServerFactoryBean bean = // 声明JAXRS服务对象
new JAXRSServerFactoryBean();
bean.setServiceBean(new UserServiceRS());// 加载服务类
bean .setAddress(“http://localhost:9004/”);// 声明地址,注意只声明地址和端口即可
bean.getInInterceptors().add(new LoggingInInterceptor());
bean.getOutInterceptors().add(new LoggingOutInterceptor());
bean.create();// 启动
System.err.println(“JAX-RS 启动成功….”);
}
}
8、使用HttpClient调用RESTful的web服务:
package cn.itcast.ws3;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
/**
* 使用URLConnection调用RESTful的服务
* 此外建议使用httpClient读取,将会更快
* 使用urlConnection可能没有返回结果
* @author 王健
* @version 1. 0 2011-11-18
*/
public class UserRsClient {
UserRsClient() throws Exception{
save2();
all();
}
/**
* 查询所有信息
* @throws Exception
*/
private void all() throws Exception{
GetMethod get = new GetMethod(“http://localhost:9004/users/all”);
get.setRequestHeader(“accept”,”application/json”);
HttpClient hc = new HttpClient();
hc.getParams().setContentCharset(“UTF-8”); // 设置编码
int code = hc.executeMethod(get);
System.err.println(” 返回的状态码:”+code);
if(code==200){
String str = get.getResponseBodyAsString();
System.err.println(” 返回信息:
“+str);
}
get.releaseConnection();
}
/**
* 保存一条信息,仍然使用GET方式
*/
private void save() throws Exception{
String name = “Jack”;// 因为是get类型,所以不能包含中文
String age = “35”;
String url = “http://localhost:9004/users/save/”+name+”/”+age;
GetMethod get = new GetMethod(url);
get.setRequestHeader(“accept”,”application/json”);
HttpClient hc = new HttpClient();
hc.getParams().setContentCharset(“UTF-8”); // 设置编码
//.setRequestHeader(“Content”,”text/html;charset=UTF-8″);
int code = hc.executeMethod(get);
System.err.println(” 返回的状态码是:”+code);
if(code==200){
String str = get.getRespons eBodyAsString();
System.err.println(” 返回的信息是:
“+str);
}
get.releaseConnection();
}
/**
* 以下使用POST方式
*/
private void save2() throws Exception{
String name = ” 王健”;//因为是get类型,所以不能包含中文
String age = “35”;
String url = “http://localhost:9004/users/add/”;
PostMethod pm = new PostMethod(url);
pm.setRequestHeader(“accept”,”application/json”);
pm.setRequestHeader(“Encoding”,”UTF-8″);
pm.setParameter(“name”,name);
pm.setParameter(“age”,age);
HttpClient hc = new HttpClient();
hc.getParams().setContentCharset(“UTF-8”);// 设置编码,否则会返回中文乱码//TODO:切记
int code = hc.execute Method(pm);
System.err.println(“Post 方式的返回值是:”+code);
if(code==200){
String ss = pm.getResponseBodyAsString();
System.err.println(“>>:”+ss);
}
pm.releaseConnection();
}
public static void main(String[] args) throws Exception {
new UserRsClient();
}
}
package cn.leaf.one;
import javax.jws.WebService;
import org.apache.cxf.jaxws.JaxWsServerFactoryBean;
/**
* 使用CXF发布一个服务
* 必须要添加WebService注解。否则不会对外暴露任何一个方法
* @author 王健
*/
@WebService
public class OneService {
public String sayHi(){ ///此方法将会对外公布
return “Good”;
}
public static void main(String[] args) throws Exception {
JaxWsServerFactoryBean bean //使用 jaxWs对其进行发布
= new JaxWsServerFactoryBean();
bean.setServiceBean(new OneService());
bean.setServiceClass(OneService.class);
bean.setAddress(“http://localhost:4444/one”);
bean.create(); //内部使用jetty服务器做为支持
System.err.println(“服务启动成功。。 “);
//Thread.sleep(1000*60*60);
//System.exit(0);
}
}
5、获取上面的wsdl文件: http://localhost:4444/one?wsdl
6、使用wsimport或是wsdl2java生成客户端调用代码,略。
7、发布一个RESTful的webService
package cn.itcast.ws3;
import java.util.ArrayList;
import java.util.List;
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 org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import cn.itcast.domain.User;
/**
* 一个基于JAX-RS的服务
* JAX-RS是无状态的服务
* 注意,必须要在JavaBean上添加@XMLRootElemet注解
* 此项目启动成功以后,可以通过以下方式访问:
* http://localhost:9004/users?_wadl&_type=xml
* 注意是_wadl&_type=xml
* 将返回一个如何调用RESTful ws的wsdl文件说明书
* @author 王健
* @version 1.0 2011-11-18
*/
@Path(value=”/users/”) //声明uri路径
@Produces(value={MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})//声明支持的类型
public class UserServiceRS {
private List users = new ArrayList();
public UserServiceRS(){
User u = new User();
u.setAge(90);
u.setName(” 大家好”);
users.add(u);
}
/**
* 以下代码,请在地址栏这样访问:
* http://localhost:9004/users/all/
* 即会以XML形式显示所有用户信息
* @return
*/
@GET
@Path(value=”/all/”)
public List getUsers(){
System.err.println(” 调用了users方法”);
return users;
}
/**
* 以下在地址栏输入:
* http://localhost:9004/users/save/Tom/34
* 其中:Tom为要保存的用户名,34为年龄
* 即会保存成功
*/
@GET
@Path(value=”/save/{name}/{age}/”)
public User save(@PathParam(“name”)String name,@PathParam(“age”)String age){
User u = new User();
u.setAge(Integer.parseInt(age));
u.setName(name);
System.err.println(” 保存成功”+u);
users.add(u);
return u;
}
/**
* 提供第二种保存方式
* 使用@FormParam方式设置接收表单的参数
* 通过HttpC lient调用,并设置请求参数
*/
@POST
@Path(value=”/add/”)
public User add(@FormParam(“name”)String name,@FormParam(“age”)String age){
User u = new User();
u.setAge(Integer.parseInt(age));
u.setName(name);
System.err.println(” 使用POST保存成功”+u);
users.add(u);
return u;
}
public static void main(String[] args) {
JAXRSServerFactoryBean bean = // 声明JAXRS服务对象
new JAXRSServerFactoryBean();
bean.setServiceBean(new UserServiceRS());// 加载服务类
bean.setAddress(“http://localhost:9004/”);// 声明地址,注意只声明地址和端口即可
bean.getInInterceptors().add(new LoggingInInterceptor());
bean.getOutInterceptors().add(new LoggingOutInterceptor());
bean.create();// 启动
System.err.println(“JAX-RS 启动成功….”);
}
}
8、使用HttpClient调用RESTful的web服务:
package cn.itcast.ws3;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
/**
* 使用URLConnection调用RESTful的服务
* 此外建议使用httpClient读取,将会更快
* 使用urlConnection可能没有返回结果
* @author 王健
* @version 1.0 2011-11-18
*/
public class UserRsClient {
UserRsClient() throws Exception{
save2();
all();
}
/**
* 查询所有信息
* @throws Excepti on
*/
private void all() throws Exception{
GetMethod get = new GetMethod(“http://localhost:9004/users/all”);
get.setRequestHeader(“accept”,”application/json”);
HttpClient hc = new HttpClient();
hc.getParams().setContentCharset(“UTF-8”); // 设置编码
int code = hc.executeMethod(get);
System.err.println(” 返回的状态码:”+code);
if(code==200){
String str = get.getResponseBodyAsString();
System.err.println(” 返回信息:
“+str);
}
get.releaseConnection();
}
/**
* 保存一条信息,仍然使用GET方式
*/
private void save() throws Exception{
String name = “Jack”;// 因为是get类型,所以不能包含中文
String age = “35”;
String url = “http://localhost:9004/users/save/”+name+”/”+age;
GetMethod get = new GetMethod(url);
get.setRequestHeader(“accept”,”application/json”);
HttpClient hc = new HttpClient();
hc.getParams().setContentCharset(“UTF-8”); // 设置编码
//.setRequestHeader(“Content”,”text/html;charset=UTF-8″);
int code = hc.executeMethod(get);
System.err.println(” 返回的状态码是:”+code);
if(code==200){
String str = get.getResponseBodyAsString();
System.err.println(” 返回的信息是:
“+str);
}
get.releaseConnection();
}
/**
* 以下使用POST方式
*/
private void save2() throws Exception{
String name = ” 王健”;//因为是get类型,所以不能包含中文
String age = “35”;
S tring url = “http://localhost:9004/users/add/”;
PostMethod pm = new PostMethod(url);
pm.setRequestHeader(“accept”,”application/json”);
pm.setRequestHeader(“Encoding”,”UTF-8″);
pm.setParameter(“name”,name);
pm.setParameter(“age”,age);
HttpClient hc = new HttpClient();
hc.getParams().setContentCharset(“UTF-8”);// 设置编码,否则会返回中文乱码//TODO:切记
int code = hc.executeMethod(pm);
System.err.println(“Post 方式的返回值是:”+code);
if(code==200){
String ss = pm.getResponseBodyAsString();
System.err.println(“>>:”+ss);
}
pm.releaseConnection();
}
public static void main(String[] args) throws Exception {
new UserRsClient();
}
}
package cn.leaf.one;
import javax.jws.WebService;
import org.apache.cxf.jaxws.JaxWsServerFactoryBean;
/**
* 使用CXF发布一个服务
* 必须要添加WebService注解。否则不会对外暴露任何一个方法
* @author 王健
*/
@WebService
public class OneService {
public String sayHi(){ ///此方法将会对外公布
return “Good”;
}
public static void main(String[] args) throws Exception {
JaxWsServerFactoryBean bean //使用 jaxWs对其进行发布
= new JaxWsServerFactoryBean();
bean.setServiceBean(new OneService());
bean.setServiceClass(OneService.class);
bean.setAddress(“http://localhost:4444/one”);
bean.create(); //内部使用jetty服务器做为支持
System.err.println(“服务启动成功。。 “);
//Thread.sleep(1000*60*60);
//System.exit(0);
}
}
5、获取上面的wsdl文件: http://localhost:4444/one?wsdl
6、使用wsimport或是wsdl2java生成客户端调用代码,略。
7、发布一个RESTful的webService
package cn.itcast.ws3;
import java.util.ArrayList;
import java.util.List;
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 org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import cn.itcast.domain.User;
/**
* 一个基于JAX-RS的服务
* JAX-RS是无状态的服务
* 注意,必须要在JavaBean上添加@XMLRootElemet注解
* 此项目启动成功以后,可以通过以下方式访问:
* http://localhost:9004/users?_wadl&_type=xml
* 注意是_wadl&_type=xml
* 将返回一个如何调用RESTful ws的wsdl文件说明书
* @author 王健
* @version 1.0 2011-11-18
*/
@Path(value=”/users/”) //声明uri路径
@Produces(value={MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})//声明支持的类型
public class UserServiceRS {
private List users = new ArrayList();
public UserServiceRS(){
User u = new User();
u.setAge(90);
u.setName(” 大家好”);
users.add(u);
}
/**
* 以下代码,请在地址栏这样访问:
* http://localhost:9004/users/all/
* 即会以XML形式显示所有用户信息
* @return
*/
@GET
@Path(value=”/all/”)
public List getUsers(){
System.err.println(” 调用了users方法”); < /div>
return users;
}
/**
* 以下在地址栏输入:
* http://localhost:9004/users/save/Tom/34
* 其中:Tom为要保存的用户名,34为年龄
* 即会保存成功
*/
@GET
@Path(value=”/save/{name}/{age}/”)
public User save(@PathParam(“name”)String name,@PathParam(“age”)String age){
User u = new User();
u.setAge(Integer.parseInt(age));
u.setName(name);
System.err.println(” 保存成功”+u);
users.add(u);
return u;
}
/**
* 提供第二种保存方式
* 使用@FormParam方式设置接收表单的参数
* 通过HttpClient调用,并设置请求参数
*/
@POST
@Path(value=”/add/”)
public User add(@FormParam(“name”)String name,@FormParam(“age”)String age){
User u = new User();
u.setAge(Integer.parseInt(age));
u.setName(name);
System.err.println(” 使用POST保存成功”+u);
users.add(u);
return u;
}
public static void main(String[] args) {
JAXRSServerFactoryBean bean = // 声明JAXRS服务对象
new JAXRSServerFactoryBean();
bean.setServiceBean(new UserServiceRS());// 加载服务类
bean.setAddress(“http://localhost:9004/”);// 声明地址,注意只声明地址和端口即可
bean.getInInterceptors().add(new LoggingInInterceptor());
bean.getOutInterceptors().add(new LoggingOutInterceptor());
bean.create();// 启动
System.err.println(“JAX-RS 启动成功….”);
}
}
package cn.itcast.ws3;
import java.util.ArrayList;
import java.util.List;
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 org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import cn.itcast.domain.User;
/**
* 一个基于JAX-RS的服务
* JAX-RS是无状态的服务
* 注意,必须要在JavaBean上添加@XMLRootElemet注解
* 此项目启动成功以后,可以通过以下方式访问:
* http://localhost:9004/users?_wadl&_type=xml
* 注意是_wadl&_type=xml
* 将返回一个如何调用RESTful ws的wsdl文件说明书
* @author 王健
* @version 1.0 2011-11-18
*/
@Path(value=”/users/”) //声明uri路径
@Produces(value={MediaType.APPLICA TION_XML,MediaType.APPLICATION_JSON})//声明支持的类型
public class UserServiceRS {
private List users = new ArrayList();
public UserServiceRS(){
User u = new User();
u.setAge(90);
u.setName(” 大家好”);
users.add(u);
}
/**
* 以下代码,请在地址栏这样访问:
* http://localhost:9004/users/all/
* 即会以XML形式显示所有用户信息
* @return
*/
@GET
@Path(value=”/all/”)
public List getUsers(){
System.err.println(” 调用了users方法”);
return users;
}
/**
* 以下在地址栏输入:
* http://localhost:9004/users/save/Tom/34
* 其中:Tom为要保存的用户名,34为年龄
* 即会保存成功
*/
@GET
@Path(value=”/save/{name}/{age}/”)
public User save(@PathParam(“name”) String name,@PathParam(“age”)String age){
User u = new User();
u.setAge(Integer.parseInt(age));
u.setName(name);
System.err.println(” 保存成功”+u);
users.add(u);
return u;
}
/**
* 提供第二种保存方式
* 使用@FormParam方式设置接收表单的参数
* 通过HttpClient调用,并设置请求参数
*/
@POST
@Path(value=”/add/”)
public User add(@FormParam(“name”)String name,@FormParam(“age”)String age){
User u = new User();
u.setAge(Integer.parseInt(age));
u.setName(name);
System.err.println(” 使用POST保存成功”+u);
users.add(u);
return u;
}
public static void main(String[] args) {
JAXRSServerFactoryBean bean = // 声明JAXRS服务对象
new JAXRSServerFactoryBean();
bean.setServiceBean(new UserServiceRS() );// 加载服务类
bean.setAddress(“http://localhost:9004/”);// 声明地址,注意只声明地址和端口即可
bean.getInInterceptors().add(new LoggingInInterceptor());
bean.getOutInterceptors().add(new LoggingOutInterceptor());
bean.create();// 启动
System.err.println(“JAX-RS 启动成功….”);
}
}
package cn.itcast.ws3;
import java.util.ArrayList;
import java.util.List;
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 org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import cn.itcast.domain.User;
/**
* 一个基于JAX-RS的服务
* JAX-RS是无状态的服务
* 注意,必须要在JavaBean上添加@XMLRo otElemet注解
* 此项目启动成功以后,可以通过以下方式访问:
* http://localhost:9004/users?_wadl&_type=xml
* 注意是_wadl&_type=xml
* 将返回一个如何调用RESTful ws的wsdl文件说明书
* @author 王健
* @version 1.0 2011-11-18
*/
@Path(value=”/users/”) //声明uri路径
@Produces(value={MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})//声明支持的类型
public class UserServiceRS {
private List users = new ArrayList();
public UserServiceRS(){
User u = new User();
u.setAge(90);
u.setName(” 大家好”);
users.add(u);
}
/**
* 以下代码,请在地址栏这样访问:
* http://localhost:9004/users/all/
* 即会以XML形式显示所有用户信息
* @return
*/
@GET
@Path(value=”/all/”)
public List getUsers(){
System.err.println(” 调用了users方法”);
return users;
}
/**
* 以下在地址栏输入:
* http://localhost:9004/users/save/Tom/34
* 其中:Tom为要保存的用户名,34为年龄
* 即会保存成功
*/
@GET
@Pat h(value=”/save/{name}/{age}/”)
public User save(@PathParam(“name”)String name,@PathParam(“age”)String age){
User u = new User();
u.setAge(Integer.parseInt(age));
u.setName(name);
System.err.println(” 保存成功”+u);
users.add(u);
return u;
}
/**
* 提供第二种保存方式
* 使用@FormParam方式设置接收表单的参数
* 通过HttpClient调用,并设置请求参数
*/
@POST
@Path(value=”/add/”)
public User add(@FormParam(“name”)String name,@FormParam(“age”)String age){
User u = new User();
u.setAge(Integer.parseInt(age));
u.setName(name);
System.err.println(” 使用POST保存成功”+u);
users.add(u);
return u;
}
public static void main(String[] args) {
JAXRSServerFactoryBean bean = // 声明JAXRS服务对象
new JAXRSServerFactoryBean();
bean.setServiceBean(new UserServiceRS());// 加载服务类
bean.setAddress(“http://localhost:9004/”);// 声明地址,注意只声明地址和端口即可
bean.getInInterceptors().add(new LoggingInIntercep tor());
bean.getOutInterceptors().add(new LoggingOutInterceptor());
bean.create();// 启动
System.err.println(“JAX-RS 启动成功….”);
}
}
8、使用HttpClient调用RESTful的web服务:
package cn.itcast.ws3;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
/**
* 使用URLConnection调用RESTful的服务
* 此外建议使用httpClient读取,将会更快
* 使用urlConnection可能没有返回结果
* @author 王健
* @version 1.0 2011-11-18
*/
public class UserRsClient {
UserRsClient() throws Exception{
save2();
all();
}
/**
* 查询所有信息
* @throws Exception
*/
private void all() throws Exception{
GetMethod get = new GetMethod(“http://localhost:9004/users/all”);
get.setRequestHeader(“accept”,”application/json”);
HttpClient hc = new HttpClient();
hc.getParams().setContentCharset(“UTF-8”); // 设置编码
int code = hc.executeMethod(get);
System.err.println(” 返回的状态码:”+code);
if(code==200){
String str = get.getResponseBodyAsString();
System.err.println(” 返回信息:
“+str);
}
get.releaseConnection();
}
/**
* 保存一条信息,仍然使用GET方式
*/
private void save() throws Exception{
String name = “Jack”;// 因为是get类型,所以不能包含中文
String age = “35”;
String url = “http://localhost:9004/users/save/”+name+”/”+age;
GetMethod get = new GetMethod( url);
get.setRequestHeader(“accept”,”application/json”);
HttpClient hc = new HttpClient();
hc.getParams().setContentCharset(“UTF-8”); // 设置编码
//.setRequestHeader(“Content”,”text/html;charset=UTF-8″);
int code = hc.executeMethod(get);
System.err.println(” 返回的状态码是:”+code);
if(code==200){
String str = get.getResponseBodyAsString();
System.err.println(” 返回的信息是:
“+str);
}
get.releaseConnection();
}
/**
* 以下使用POST方式
*/
private void save2() throws Exception{
String name = ” 王健”;//因为是get类型,所以不能包含中文
String age = “35”;
String url = “http://localhost:9004/users/add/”;
PostMethod pm = new PostMethod(url);
pm.setRequestHeader(“accept”,”applicati on/json”);
pm.setRequestHeader(“Encoding”,”UTF-8″);
pm.setParameter(“name”,name);
pm.setParameter(“age”,age);
HttpClient hc = new HttpClient();
hc.getParams().setContentCharset(“UTF-8”);// 设置编码,否则会返回中文乱码//TODO:切记
int code = hc.executeMethod(pm);
System.err.println(“Post 方式的返回值是:”+code);
if(code==200){
String ss = pm.getResponseBodyAsString();
System.err.println(“>>:”+ss);
}
pm.releaseConnection();
}
public static void main(String[] args) throws Exception {
new UserRsClient();
}
}
package cn.itcast.ws3;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.h ttpclient.methods.PostMethod;
/**
* 使用URLConnection调用RESTful的服务
* 此外建议使用httpClient读取,将会更快
* 使用urlConnection可能没有返回结果
* @author 王健
* @version 1.0 2011-11-18
*/
public class UserRsClient {
UserRsClient() throws Exception{
save2();
all();
}
/**
* 查询所有信息
* @throws Exception
*/
private void all() throws Exception{
GetMethod get = new GetMethod(“http://localhost:9004/users/all”);
get.setRequestHeader(“accept”,”application/json”);
HttpClient hc = new HttpClient();
hc.getParams().setContentCharset(“UTF-8”); // 设置编码
int code = hc.executeMethod(get);
System.err.println(” 返回的状态码:”+code);
if(code==200){
String str = get.getResponseBodyAsString();
System.err.println(” 返回信息:
“+str);
}
get.releaseConnection();
}
/**
* 保存一条信息,仍然使用GET方式
*/
private void save() throws Exception{
String name = “Jack”;// 因为是get类型,所以不能包含中文
String age = “35”;
String url = “http://localhost:9004/users/save/”+name+”/”+age;
GetMethod get = new GetMethod(url);
get.setRequestHeader(“accept”,”application/json”);
HttpClient hc = new HttpClient();
hc.getParams().setContentCharset(“UTF-8”); // 设置编码
//.setRequestHeader(“Content”,”text/html;charset=UTF-8″);
int code = hc.executeMethod(get);
System.err.println(” 返回的状态码是:”+code);
if(code==200){
String str = get.getResponseBodyAsString();
System.err.println(” 返回的信息是:
“+str);
}
get.releaseConnection ();
}
/**
* 以下使用POST方式
*/
private void save2() throws Exception{
String name = ” 王健”;//因为是get类型,所以不能包含中文
String age = “35”;
String url = “http://localhost:9004/users/add/”;
PostMethod pm = new PostMethod(url);
pm.setRequestHeader(“accept”,”application/json”);
pm.setRequestHeader(“Encoding”,”UTF-8″);
pm.setParameter(“name”,name);
pm.setParameter(“age”,age);
HttpClient hc = new HttpClient();
hc.getParams().setContentCharset(“UTF-8”);// 设置编码,否则会返回中文乱码//TODO:切记
int code = hc.executeMethod(pm);
System.err.println(“Post 方式的返回值是:”+code);
if(code==200){
String ss = pm.getResponseBodyAsString();
System.err.println(“>>:”+ss);
}
pm.releaseConnection();
}
public st atic void main(String[] args) throws Exception {
new UserRsClient();
}
}
package cn.itcast.ws3;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
/**
* 使用URLConnection调用RESTful的服务
* 此外建议使用httpClient读取,将会更快
* 使用urlConnection可能没有返回结果
* @author 王健
* @version 1.0 2011-11-18
*/
public class UserRsClient {
UserRsClient() throws Exception{
save2();
all();
}
/**
* 查询所有信息
* @throws Exception
*/
private void all() throws Exception{
GetMethod get = new GetMethod(“http://localhost:9004/users/all”);
get.setRequestHeader(“accept”,”application/json”);
HttpClient hc = new HttpClient();
hc.getParams().setContentCharset(“UTF-8”); // 设置编码
int code = hc.executeMethod(get);
System .err.println(” 返回的状态码:”+code);
if(code==200){
String str = get.getResponseBodyAsString();
System.err.println(” 返回信息:
“+str);
}
get.releaseConnection();
}
/**
* 保存一条信息,仍然使用GET方式
*/
private void save() throws Exception{
String name = “Jack”;// 因为是get类型,所以不能包含中文
String age = “35”;
String url = “http://localhost:9004/users/save/”+name+”/”+age;
GetMethod get = new GetMethod(url);
get.setRequestHeader(“accept”,”application/json”);
HttpClient hc = new HttpClient();
hc.getParams().setContentCharset(“UTF-8”); // 设置编码
//.setRequestHeader(“Content”,”text/html;charset=UTF-8″);
int code = hc.executeMethod(get);
System.err.println(” 返回的状态码是:”+code);
if(code==200){
String str = get.getResponseBodyAsString();
System.err.println(” 返回的信息是:
“+str);
}
get.releaseConnection();
}
/**
* 以下使用POST方式
*/
private void save2() thro ws Exception{
String name = ” 王健”;//因为是get类型,所以不能包含中文
String age = “35”;
String url = “http://localhost:9004/users/add/”;
PostMethod pm = new PostMethod(url);
pm.setRequestHeader(“accept”,”application/json”);
pm.setRequestHeader(“Encoding”,”UTF-8″);
pm.setParameter(“name”,name);
pm.setParameter(“age”,age);
HttpClient hc = new HttpClient();
hc.getParams().setContentCharset(“UTF-8”);// 设置编码,否则会返回中文乱码//TODO:切记
int code = hc.executeMethod(pm);
System.err.println(“Post 方式的返回值是:”+code);
if(code==200){
String ss = pm.getResponseBodyAsString();
System.err.println(“>>:”+ss);
}
pm.releaseConnection();
}
public static void main(String[] args) throws Exception {
new UserRsClient();
}
}