CXF-based JAX-WS, JAX-RS (Restful) WebService

1. Preparation

< div style="font-family:Verdana,Geneva,Arial,Helvetica,sans-serif; font-size:13px; background-color:rgb(40,85,126)"> This is a basic CXF-based Java project< br> If you only publish JAX-WS applications, you need the following jar files:
cxf-2.4.2.jar This is the core package of CXF
xmlschema-core-2.0.jar This is the parsing of the apache schema
> neethi-3.0.1.jar package apache’s WebService strategy package
wsdl4j-1.6.2.jar I won’t use more wsdl file generation package
servlet-api.jar. .

jetty-util-7.4.5 .v20110725.jar //Because CXF uses an embedded jetty server, the following are all jetty server packages.
jetty-server-7.4.5.v20110725.jar
jetty-http-7.4.5.v20110725.jar
jetty-io-7.4.5.v20110725.jar
jetty-continuation-7.4 .5.v20110725.jar
​ < /div>

2,
If you need to use JAX-RS to publish RESTful services, add it The following jar file:
jsr311-api-1.1.1.jar / This is the new standard of WebService issued by SUN. This JSR311 package contains what annotations should be added to the class, such as @Post
If you need to return JSON-type strings need to be added again
jettison-1.3.jar //
Because cxf uses this type of JSON string to parse.
(For a jax-rs application , The first method must return a JavaBean,
cannot have no return value, and the @XmlRootElement annotation must be used on the class)
(to be continued)
3.

CXF publishing service class:
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.

4. Use CXF to publish a service
package cn.leaf.one;
import javax.jws.WebService;
import org.apache.cxf. jaxws.JaxWsServerFactoryBean;
/**
* Use CXF to publish a service
* WebService annotation must be added. Otherwise, no method will be exposed to the outside
* @author 王健
*/
@WebService
public class OneService {< /div>

public String sayHi(){ ///This method will be publicly announced
return “Good”;
}
public static void main(String[] args) throws Exception {
JaxWsServerFactoryBean bean //Use jaxWs to publish it
= new JaxWsServerFactoryBean();
bean. setServiceBean(new OneService());
bean.setServiceClass(OneService.class);
bean.setAddress(“http://localhost:4444/one”);

div>

bean.create(); //Internal use jetty server as support
System.err.println(“Service started successfully…”);
/ /Thread.sleep(1000*60*60);
//System.exit(0);
}
}
5. Get the above Wsdl file: http://localhost:4444/one?wsdl
6. Use wsimport or wsdl2java to generate client calling code, omitted.
7. Publish a RESTful webService
package cn.itcast.ws3;
import java.util .ArrayList;
import java.util.List;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET; < /div>

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; < /div>

import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import cn.itcast.domain.User ;
/**
* A service based on JAX-RS
* JAX-RS is a stateless service
* Note that @XMLRootElemet annotation must be added to JavaBean
* After this project is successfully launched, you can access it in the following ways:
* http://localhost:9004/users?_wadl&_type=xml
* Note that _wadl&_type=xml

div>

* Will return a wsdl file manual on how to call RESTful ws
* @author 王健
* @version 1.0 2011-11-18

< div> */

@Path(value=”/users/”) //Declare uri path
@Produces(value={MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})/ /Declaration of supported types
public class UserServiceRS {
private List users = new ArrayList();
public UserServiceRS(){
User u = new User();
u.setAge(90);
u.se tName(“Hello everyone”);
users.add(u);
}
/**
* The following code , Please visit in the address bar like this:
* http://localhost:9004/users/all/
* All user information will be displayed in XML format

< div> * @return

*/
@GET
@Path(value=”/all/”)
public List getUsers(){
System.err.println(“The users method is called”);
return users;
}
/**
* Enter the following in the address bar:
* http://localhost:9004/users/save/Tom/34
* Among them: Tom is the user name to be saved, 34 is the age
* It will be saved successfully
*/
@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(” save Success “+u);
users.add(u);
return u;
}
/**

* Provide a second saving method
* Use @FormParam to set the parameters of the received form
* Call via HttpClient and set the request parameters

< div> */

@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.set Name(name);
System.err.println(“Save successfully using POST”+u);
users.add(u);
return u;
}
public static void main(String[] args) {
JAXRSServerFactoryBean bean = // Declare JAXRS service object
new JAXRSServerFactoryBean();
bean.setServiceBean(new UserServiceRS());// Load service class
bean.setAddress(“http://localhost:9004/”) ;// Declare the address, note that only the address and port can be declared
bean.getInInterceptors().add(new LoggingInInterceptor());
bean.getOutInterceptors().add( new LoggingOutInterceptor());
bean.create();// start
System.err.println(“JAX-RS started successfully…”);

div>

}
}

8. Use HttpClient to call RESTful web services:
package cn.itcast.ws3;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
/**
* Use URLConnection to call RESTful services
* In addition, it is recommended to use httpClient to read, which will be faster
* Using urlConnection may not return results
* @author Wang Jian
* @version 1.0 2011-11-18
*/
public class UserRsClient {
UserRsClient() throws Exception {
save2();
all();
}
/**
* Query All information
* @throws Ex ception
*/
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”); // Set the encoding
int code = hc.executeMethod(get);
System.err.println(” Returned status Code: “+code);
if(code==200){
String str = get.getResponseBodyAsString();
System.err.println (” Return information:
“+str);
}
get.releaseConnection();
}
/* *
* To save a message, still use the GET method
*/
priv ate 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);

< div> get.setRequestHeader(“accept”,”application/json”);

HttpClient hc = new HttpClient();
hc.getParams().setContentCharset(“UTF- 8”); // Set the encoding
//.setRequestHeader(“Content”,”text/html;charset=UTF-8″);
int code = hc.executeMethod (get);
System.err.println(” The status code returned is: “+code);
if(code==200){
String str = get.getResponseBodyAsString();
System.err.println(” The information returned is:
“+str);
}
get.re leaseConnection();
}
/**
* The following uses POST method
*/
private void save2() throws Exception{
String name = “王健”;//Because it is a get type, it cannot contain Chinese
String age = “35”;
div>

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){
String ss = pm.getResponseBodyAsString();
System.err.println(“>>:”+ss);
}
pm.releaseConnection();
}
public static void main(String[] args) throws Exception {
new UserRsClient();
}
} < /div>

1, preparation

This is a basic CXF-based Java Project
If you only publish JAX-WS applications, you need the following jar files:
cxf-2.4.2.jar This is the core package of CXF
xmlschema-core-2.0.jar Schema package of apache This is the analysis
neethi-3.0.1.jar package apache’s WebService strategy package
wsdl4j-1.6.2.jar I don’t use more wsdl file generation package
servlet- api. .

jetty-util-7.4.5.v20110725.jar //Because CXF uses an embedded jetty server, the following are all jetty server packages.
jetty-server-7.4.5.v20110725.jar
jetty-http-7.4.5.v20110725.jar
jetty-io-7.4.5.v20110725.jar
jetty-continuation-7.4 .5.v20110725.jar

2,

If you need to use JAX-RS to publish RESTful services, add the following jar file:
jsr311 -api-1.1.1.jar /This is a new standard for WebService issued by Sun. This JSR311 package contains what annotations should be added to the class, such as @Post
If you need to return a JSON type string, you need to add it again
jettison-1.3.jar //
Because cxf uses this type to parse JSON strings.

(For a jax-rs application, the first method must return a JavaBean,
There must be no return value, and the @XmlRootElement annotation must be used on the class)

p>

(to be continued)

3,

CXF publishing service class:
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.

4. Use CXF to publish a service
package cn.leaf.one;
import javax.jws.WebService;
import org.apache.cxf. jaxws.JaxWsServerFactoryBean;
/**
* Use CXF to publish a service
* WebService annotation must be added. Otherwise, no method will be exposed to the outside
* @author 王健
*/
@WebService
public class OneService {< /div>

public String sayHi(){ ///This method will be publicly announced
return “Good”;
}
public static void main(String[] args) throws Exception {
JaxWsServerFactoryBean bean //Use jaxWs to publish it
= new JaxWsServerFactoryBean();
bean. setServiceBean(new OneService());
bean.setServiceClass(OneService.class);
bean.setAddress(“http://localhost:4444/one”);

div>

bean.create(); //Internal use jetty server as support
System.err.println(“Service started successfully…”);
/ /Thread.sleep(1000*60*60);
//System.exit(0);
}
}
5. Get the above wsdl file: http://localhost:4444/one?wsdl
6. Use wsimport or wsdl2java to generate client calling code, omitted.
7. Publish a RESTful webService
package cn.itcast.ws3;
import java.util .ArrayList;
import java.util.List;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET; < /div>

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; < /div>

import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import cn.itcast.domain.User ;
/**
* A service based on JAX-RS
* JAX-RS is a stateless service
* Note that @XMLRootElemet annotation must be added to the JavaBean
* After the project is successfully launched, you can access it in the following ways:
* http://localhost:9004/users?_wadl&_type=xml
* Note that _wadl&_type=xml
* Will return a wsdl file for how to call RESTful ws Manual
* @author 王健
* @version 1.0 2011-11-18
*/
@Path(value= “/users/”) //Declare uri path
@Produces(value={MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})//Declare supported types
public class UserServiceRS {
private List users = new ArrayList();
public UserServiceRS(){
User u = new User(); < /div>

u.setAge(90);
u.setName(“Hello everyone”);
users.add(u);
}
/**
* The following code, please visit in the address bar like this:
* http://localhost:9004/users/all/
* That is All user information will be displayed in XML format
* @return
*/
@GET
@Path(value=”/ all/”)
public List getUsers(){
System.err.println(“The users method is called”);
return users ;
}
/**
* Enter the following in the address bar:
* http://localhost:9004/users /save/Tom/34
* Among them: Tom is the user name to be saved, 34 is the age
* It will be saved successfully
*/

@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(“Save successfully”+u);
users.add(u);
return u;
}
/**
* Provide the second saving method
* Use @FormParam to set the parameters of the received form
* Call through HttpClient and set the request parameters
*/

@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(“Save successfully using POST”+u);
users.add(u);
return u;
}
public static void ma in(String[] args) {
JAXRSServerFactoryBean bean = // Declare JAXRS service object
new JAXRSServerFactoryBean();
bean.setServiceBean(new UserServiceRS( ));// Load the service class
bean.setAddress(“http://localhost:9004/”);// Declare the address, note that only the address and port can be declared
bean.getInInterceptors().add(new LoggingInInterceptor());
bean.getOutInterceptors().add(new LoggingOutInterceptor());
bean.create();/ / Start
System.err.println(“JAX-RS started successfully…”);
}
}

8. Use HttpClient to call RESTful web services:
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();

}
/**
* 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){

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();

}

}

Leave a Comment

Your email address will not be published.