二、cxf框架实现REST风格http协议的WebService(JAX-RS标准)

版权声明:本篇文章由IT_CREATE整理 https://blog.csdn.net/IT_CREATE/article/details/86642980

上一章我已经讲了cxf框架实现soap协议的WebService(JAX-WS的标准)

下面我开始讲第二种WebService的客户端和服务器的创建,利用 cxf框架和 REST风格http协议来实现,使用JAX-RS标准。传输是利用xml格式进行传输。

京东万象服务接口文档的样子:https://wx.jdcloud.com/market/datas/31/11073

服务器和客户端我都用的maven创建的web项目

1、首先导入相关jar包

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.gezhi</groupId>
	<artifactId>webservices</artifactId>
	<packaging>war</packaging>
	<version>1.0</version>
	<name>webservices Maven Webapp</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<junit.version>4.12</junit.version>
		<log4j.version>1.2.17</log4j.version>
		<spring.version>4.3.14.RELEASE</spring.version>
		<cxf.version>3.2.0</cxf.version>

	</properties> 

	<dependencies>


		<!-- 这下面2中JAR包,主要是引入SUN制定的JAX-WS标准的相关组件 -->
		<dependency>
			<groupId>org.apache.cxf</groupId>
			<artifactId>cxf-rt-frontend-jaxws</artifactId>
			<version>${cxf.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.cxf</groupId>
			<artifactId>cxf-rt-transports-http</artifactId>
			<version>${cxf.version}</version>
		</dependency>

		<!-- 这下面2中JAR包,主要是引入SUN制定的JAX-RS标准的相关组件 -->
		<dependency>
			<groupId>org.apache.cxf</groupId>
			<artifactId>cxf-rt-frontend-jaxrs</artifactId>
			<version>${cxf.version}</version>
		</dependency>

		<dependency>
			<groupId>org.apache.cxf</groupId>
			<artifactId>cxf-rt-rs-service-description</artifactId>
			<version>${cxf.version}</version>
		</dependency>


		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>


	</dependencies>
	<build>
		<finalName>webservices</finalName>

		<pluginManagement>
			<!-- 配置maven 在构建项目时,采用相关插件 -->
			<plugins>
				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-compiler-plugin</artifactId>
					<version>3.8.0</version>
					<configuration>
						<source>1.8</source>
						<target>1.8</target>
					</configuration>
				</plugin>
			</plugins>
		</pluginManagement>

	</build>
</project>

2、定义你要传输的数据(这里是对象)

比如这里我想通过服务接口来提供客户信息,那么客户端在调用我的服务接口的时候就可以获得客户信息了。

客户类(CustomBean)

package com.ge.webservices.bean;

import java.io.Serializable;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
 * 客户实体
 * @author Administrator
 *
 */
@XmlRootElement
public class CustomBean implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = -3394356866657413885L;

	private Long id;
	private String customerName;
	private String loginName;
	private String password;
	private Integer age;
	private Integer gender;

	private List<OrderBean> orders;

	public CustomBean() {
		super();
		// TODO Auto-generated constructor stub
	}
	
	public CustomBean(String customerName) {
		super();
		this.customerName = customerName;
	}


	@XmlAttribute
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	
	@XmlElement
	public String getCustomerName() {
		return customerName;
	}
	public void setCustomerName(String customerName) {
		this.customerName = customerName;
	}
	@XmlElement
	public String getLoginName() {
		return loginName;
	}
	public void setLoginName(String loginName) {
		this.loginName = loginName;
	}
	@XmlElement
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	@XmlElement
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	@XmlElement
	public Integer getGender() {
		return gender;
	}
	public void setGender(Integer gender) {
		this.gender = gender;
	}
	@XmlElement
	public List<OrderBean> getOrders() {
		return orders;
	}

	public void setOrders(List<OrderBean> orders) {
		this.orders = orders;
	}

	@Override
	public String toString() {
		return "CustomBean [id=" + id + ", customerName=" + customerName + ", loginName=" + loginName + ", password="
				+ password + ", age=" + age + ", gender=" + gender + ", orders=" + orders + "]";
	}
	
}

对象的传输这次用的是xml格式进行传输

@XmlRootElement注解放在类上,作用是将这个类的类名作为xml的根节点

@XmlAttribute 注解把该属性作为根结点的一个属性,比如这里<customBean id="">转换之后就可以指定具体的实体了

@XmlElement注解可以放在属性上,参数上,get方法上;指定这些属性是xml的子节点

订单类(OrderBean):客户类中含有订单数据

package com.ge.webservices.bean;

import java.io.Serializable;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class OrderBean implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = -5608376596838086631L;
	private Long id;
	private String orderNo;

	public OrderBean() {
		super();
		// TODO Auto-generated constructor stub
	}
	
	
	public OrderBean(Long id, String orderNo) {
		super();
		this.id = id;
		this.orderNo = orderNo;
	}


	@XmlElement
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	@XmlElement
	public String getOrderNo() {
		return orderNo;
	}
	public void setOrderNo(String orderNo) {
		this.orderNo = orderNo;
	}
	@Override
	public String toString() {
		return "OrderBean [id=" + id + ", orderNo=" + orderNo + "]";
	}	
	
}

数据返回消息类(ResMessage):这里我把客户放在消息对象中进行传输出去,也可直接返回客户信息,那么在接口的方法上的返回就直接写客户类,那么客户端也可以拿到这个客户的信息,但是我用一个消息返回类去做返回,我就可以返回任何对象了,只需要向消息类中去装填就可以了,即使我返回的是其他信息。

package com.ge.webservices.bean;

import java.io.Serializable;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;

/**
 * @XmlSeeAlso(value = { CustomBean.class,OrderBean.class }) 该注解的作用:提前让这个类对关联类有所认知
 * 方便XML进行相关的解析
 * @author Administrator
 *
 */
@XmlSeeAlso(value = { 
		CustomBean.class,
		OrderBean.class 
		})
@XmlRootElement
public class ResMessage implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = -7370451209320869930L;

	private boolean status;
	private Integer statusCode;
	private String msg;

	private List<?> datas;

	public ResMessage() {
		super();
		// TODO Auto-generated constructor stub
	}

	public ResMessage(boolean status, Integer statusCode, String msg) {
		super();
		this.status = status;
		this.statusCode = statusCode;
		this.msg = msg;
	}

	@XmlElement
	public boolean isStatus() {
		return status;
	}

	public void setStatus(boolean status) {
		this.status = status;
	}

	@XmlElement
	public Integer getStatusCode() {
		return statusCode;
	}

	public void setStatusCode(Integer statusCode) {
		this.statusCode = statusCode;
	}

	@XmlElement
	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public List<?> getDatas() {
		return datas;
	}

	public void setDatas(List<?> datas) {
		this.datas = datas;
	}

	@Override
	public String toString() {
		return "ResMessage [status=" + status + ", statusCode=" + statusCode + ", msg=" + msg + ", datas=" + datas
				+ "]";
	}
}

消息类中有个datas属性,是用来装信息的,因为用了泛型,所以可以装填任何类型的数据;除了用之前两个类都用了的@XmlRootElement、@XmlElement注解,还需要用到一个注解,@XmlSeeAlso。

@XmlSeeAlso注解的作用是提前让这个类对关联类有所认知,因为我们用了泛型,所以对于datas装什么并不知道,所以需要提前指定,在转xml的时候才能识别,完成转换。

3、定义你要提供的服务接口

package com.ge.webservices.rest;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

import com.ge.webservices.bean.CustomBean;

@Path("/customs")
public interface RestWebService {

	/**
	 * 新增实现
	 * @POST 将该方法声明为一个新增方法 
	 * @Path 声明路径    ---uri:   /customs/{id}
	 * 
	 * @param custom
	 * @return
	 */
	@POST
	@Path("/{id}")
	Response saveCustomBean(CustomBean custom);
	/**
	 * 修改实现
	 * @PUT 将该方法声明为一个修改方法 
	 * @Path 声明路径    ---uri:   /customs/{id}
	 * 
	 * @param custom
	 * @return
	 */
	@PUT
	@Path("/{id}")
	Response updateCustomBean(CustomBean custom,@PathParam("id")Long id);
	
	/**
	 * 删除实现
	 * @DELETE 将该方法声明为一个删除方法 
	 * @Path 声明路径    ---uri:   /customs/{id}
	 * 
	 * @param custom
	 * @return
	 */
	@DELETE
	@Path("/{id}")
	Response deleteCustomBeanById(@PathParam("id") Long id);
	
	
	/**
	 * 查询实现
	 * @GET 将该方法声明为一个查询方法 
	 * @Path 声明路径    ---uri:   /customs/{id}
	 * 
	 * @param custom
	 * @return
	 */
	@GET
	@Path("/{id}")
	Response getCustomBeanById(@PathParam("id") Long id);
	
	@GET
	@Path("/{loginName}/{password}")
	Response findCustomBeanByLoginNameAndPassword(@PathParam("loginName") String loginName,@PathParam("password")String password);
	
}

@Path注解声明路径,你可以把他想象成和@RequestMapping注解的作用差不多,可以放在类上和方法上,不过这个是用在WebService中的

@POST、@PUT、@DELETE、@GET分别指定方法的接收请求的类型,对应的就是那四种请求类型

@PathParam注解作用是获取 { } 里面的值,跟@PathVariable注解的意思差不多,不过这个是用在WebService中的

方法的返回必须是 Response 

4、对服务接口进行实现(写一个类实现你写的服务接口)

package com.ge.webservices.rest.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.core.Response;
import com.ge.webservices.bean.CustomBean;
import com.ge.webservices.bean.OrderBean;
import com.ge.webservices.bean.ResMessage;
import com.ge.webservices.rest.RestWebService;
import com.ge.webservices.util.JAXBTool;

public class RestWebServiceImpl implements RestWebService {

	/**
	 * 定义一个Map,用来模拟数据库完成数据的CRUD
	 */
	Map<Long, CustomBean> customs = new HashMap<Long, CustomBean>();

	@Override
	public Response saveCustomBean(CustomBean custom) {
		// TODO Auto-generated method stub
		// 返回处理结果
		ResMessage res = new ResMessage(true, 10000, "操作成功!");
		try {
			Long id = (long) (Math.random() * 10000);// 得到一个0-10000的一个随机值
			System.out.println(id);
			custom.setId(id);// 覆盖custom中的ID值
			customs.put(id, custom);// 向MAP中存储数据

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			res.setStatus(false);
			res.setStatusCode(10001);
			res.setMsg("系统繁忙,请稍后重试!");
		}

		return Response.ok(res).build();
	}

	@Override
	public Response updateCustomBean(CustomBean custom, Long id) {
		// TODO Auto-generated method stub
		// 返回处理结果
		ResMessage res = new ResMessage(true, 10000, "操作成功!");
		try {
			customs.put(id, custom);// 向MAP中存储数据
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			res.setStatus(false);
			res.setStatusCode(10001);
			res.setMsg("系统繁忙,请稍后重试!");
		}

		return Response.ok(res).build();
	}

	@Override
	public Response deleteCustomBeanById(Long id) {
		// TODO Auto-generated method stub
		// 返回处理结果
		ResMessage res = new ResMessage(true, 10000, "操作成功!");
		try {
			customs.remove(id);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			res.setStatus(false);
			res.setStatusCode(10001);
			res.setMsg("系统繁忙,请稍后重试!");
		}

		return Response.ok(res).build();
	}

	@Override
	public Response getCustomBeanById(Long id) {
		// TODO Auto-generated method stub
		CustomBean custom = null;
		try {
			if (customs.containsKey(id)) {
				custom = customs.get(id);

				List<OrderBean> orders = new ArrayList<>();
				orders.add(new OrderBean(1L, "9512"));
				orders.add(new OrderBean(2L, "9527"));
				custom.setOrders(orders);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

		return Response.ok(custom).build();
	}

	@Override
	public Response findCustomBeanByLoginNameAndPassword(String loginName, String password) {
		// TODO Auto-generated method stub
		// 返回处理结果
		ResMessage res = new ResMessage(true, 10000, "操作成功!");
		try {
			List<OrderBean> orders = new ArrayList<>();
			orders.add(new OrderBean(1L, "9512"));
			orders.add(new OrderBean(2L, "9527"));
			
			
			
			List<CustomBean> customs = new ArrayList<>();
			
			CustomBean custom01 = new CustomBean("张三");
			custom01.setOrders(orders);
			
			customs.add(custom01);
			
			CustomBean custom02 = new CustomBean("张大麻子");
			custom02.setOrders(orders);
			
			
			customs.add(custom02);
			res.setDatas(customs);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			res.setStatus(false);
			res.setStatusCode(10001);
			res.setMsg("系统繁忙,请稍后重试!");
		}

		return Response.ok(res).build();

	}

}

这个类就是对你接口中的方法进行实现,怎么实现,看你的业务。

最后返回用 Response.ok(需要装填的数据).build()  它会返回一个Response 对象,需要装的数据就是你要返回的对象实体。必须是对象。

5、编写配置文件 cxf-bean.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:jaxrs="http://cxf.apache.org/jaxrs"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">




	<!--id名字随便起,主要是在sping容器中作为组件id,address路径随便写,主要是作为找到你服务的路径 -->
	<!-- 在spring容器中,发布REST 风格的WEB Service接口 -->
	<jaxrs:server id="customService" address="/custommag">
		<jaxrs:serviceBeans>
			<ref bean="restWebServiceImpl"/>
		</jaxrs:serviceBeans>
	</jaxrs:server>

	<!-- 关联你的借口实现类 -->
	<bean id="restWebServiceImpl" class="com.ge.webservices.rest.impl.RestWebServiceImpl"></bean>

	<!-- 如果有多个,就继续发布…… -->


</beans>

6、在web.xml文件中进行一些配置(引入cxf-bean.xml)

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  
  <!-- REST 架构风格的WebService启动方式 -->
  <context-param>
  	<param-name>contextConfigLocation</param-name>
  	<!-- 如果存在多个配置文件,都需要交给容器,那么文件之间采用,分割 -->
  	<param-value>classpath:cxf-bean.xml</param-value>
  </context-param>
  
  <!-- 设置监听器,来启动 classpath:cxf-bean.xml-->
  <listener>
  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <!-- SOAP协议的WEBService启动方式 -->
  <!-- 启动cxf框架的核心控制器,并启动spring容器,完成WEB服务的注册 -->
  <servlet>
  	<servlet-name>cxf</servlet-name>
  	<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
  	<!--这个就不需要了,如果是SOAP就用这种启动方式
	<init-param>
  		<param-name>config-location</param-name>
  		<param-value>classpath:cxf-servlet.xml</param-value>
  	</init-param>-->
  </servlet>
  <servlet-mapping>
  	<servlet-name>cxf</servlet-name>
  	<!-- 需要区分:与SpringMVC框架的路径请求 -->
  	<url-pattern>/services/*</url-pattern>
  </servlet-mapping>
  
</web-app>

上面相当于服务端已经创建完毕了。

7、客户端的编写(服务器端用了哪些包,客户端也用这些包,同时引入下面这些包,commons-httpclient这个包最主要,其他的是测试相关的)

<!-- 引入HttpClient 组件JAR包(完成:后台模拟浏览器向服务器发起HTTP请求) -->
<dependency>
	<groupId>commons-httpclient</groupId>
	<artifactId>commons-httpclient</artifactId>
	<version>${commons.httpclient.version}</version>
</dependency>


<!-- 引入spring整合junit的jar包,不过这个我没用,因为测试很简单,我没用什么框架,很简单的测试代码,junit就可以了-->
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-test</artifactId>
	<version>${spring.version}</version>
</dependency>

<!-- 导入junit单元测试框架JAR包 -->
<dependency>
	<groupId>junit</groupId>
	<artifactId>junit</artifactId>
	<version>${junit.version}</version>
	<scope>test</scope>
</dependency>


<!-- 导入LOG4J日志框架JAR包 -->
<dependency>
	<groupId>log4j</groupId>
	<artifactId>log4j</artifactId>
	<version>${log4j.version}</version>
</dependency>

开启服务器端tomcat容器,然后就可以通过http://localhost:8080/项目名/services/ 这个地址去访问 Available RESTful services页面:

红色这条线的路径就是你客户端要访问的路径

我们点开WADL这个路径,可以看到:

不过这不是重点。因为服务接口提供方会提供文档说明。

然后我们看这里:

我们通过这里就可以看到了提供服务的有5个方法,因为有五个请求,请求路径也能看到:

http://localhost:8080/webservices/services/custommag/customs/{id}

http://localhost:8080/webservices/services/custommag/customs/{loginName}/{password}

这两个路径对应的请求类型也能看出来,下面我不在说这个怎么看了,并且因为路径使我们自己写的,所以都很清楚。进入实际代码编写。

首先在服务器端我们写了三个用于装数据的类,分别是CustomBean、OrderBean、ResMessage,那么我们在客户端也要用到这三个类,因为这三个类是要用来接收返回信息的,我们在服务器端的方法返回的就是这几个对象。一般情况下,服务提供方都会告诉我们请求路径,请求方法,请求参数和相应返回参数,如果我们是提供方,这些也要写清楚。

我们把服务端的装数据的这三个类的代码拷贝一份到客户端待用(接下来就是客户端代码)

这里我就以测试接口中的findCustomBeanByLoginNameAndPassword()方法为例:(这个方法我们在服务器用的是get请求)

@Test
public void findCustomBeanByLoginNameAndPassword() {

   //绑定请求路径产生一个请求,有GetMethod、PostMethod、DeleteMethod、PutMethod
	GetMethod get = new GetMethod("http://localhost:8080/webservices/services/custommag/customs/zs/123456");
	try {
		//执行HTTP方法,调用下面的自己写的handleHttpMethod	方法		
		handleHttpMethod(get);
		//获得GET方法,返回的结果
		String res = get.getResponseBodyAsString();
		System.out.println(res);
		if(!StringUtils.isEmpty(res)) {
			//转换成JAVA对象
			System.out.println(JAXBTool.xml2Java(ResMessage.class, res));
		}
			
	} catch (Exception e) {
		// TODO: handle exception
		e.printStackTrace();
	}
}

//执行请求的方法
private void handleHttpMethod(HttpMethod method) {
	// TODO Auto-generated method stub
	HttpClient client = new HttpClient();
	int statusCode = 0;
		
	try {
		//设置请求头,指定传过去的消息是格式是xml,编码是utf-8	
		method.setRequestHeader("Accept", "application/xml;charset=utf-8");
			
		//执行HTTP方法,并返回响应码,就是404,405,500这类的
		statusCode = client.executeMethod(method);
			
		//根据返回的状态码,转换对应的状态枚举
		Response.Status status = Response.Status.fromStatusCode(statusCode);
		if(status == Response.Status.OK) {
			System.out.println("后台处理完毕!");
		}else if(status == Response.Status.NOT_FOUND) {
			System.out.println("请求路径错误!");
		}else if(status == Response.Status.METHOD_NOT_ALLOWED) {
			System.out.println("请求方法不被允许!");
		}
			
//		……
	} catch (Exception e) {
		// TODO: handle exception
		e.printStackTrace();
	}
}

JAXBTool这个工具类可以实现xml和对象的互转,工具地址:https://blog.csdn.net/IT_CREATE/article/details/86599715

这个工具有两个方法:

String java2Xml(Class<T> cls,Object obj) 前面是你要转的类,后面是你具体的对象

Object xml2Java(Class<T> cls,String content) 前面是你要转的类,后面是xml字符串

我们这次从服务器传出来的是对象序列化的xml字符串,所以需要这个工具来转成具体的对象。

下面是完整测试代码:

package com.ge.webservices.soap.client;

import java.io.ByteArrayInputStream;
import javax.ws.rs.core.Response;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.junit.Test;
import org.springframework.util.StringUtils;
import com.gezhi.webservices.soap.util.JAXBTool;

public class RestClientTest {

	private String id = "";
	
	
	@Test
	public void findCustomBeanByLoginNameAndPassword() {
		GetMethod get = new GetMethod("http://localhost:8080/webservices/services/custommag/customs/zs/123456");
		try {
			//执行HTTP方法			
			handleHttpMethod(get);
			//获得GET方法,返回的结果
			String res = get.getResponseBodyAsString();
			System.out.println(res);
			if(!StringUtils.isEmpty(res)) {
				//转换成JAVA对象
				System.out.println(JAXBTool.xml2Java(ResMessage.class, res));
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	
	
	
	@Test
	public void deleteCustomBeanById() {
		DeleteMethod delete = new DeleteMethod("http://localhost/webservices/services/custommag/customs/"+id);
		try {
			//执行HTTP方法			
			handleHttpMethod(delete);
			//获得Delete方法,返回的结果
			String res = delete.getResponseBodyAsString();
			
			//转换成JAVA对象
			System.out.println(JAXBTool.xml2Java(ResMessage.class, res));
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	
	
	@Test
	public void getCustomBeanById() {
		GetMethod get = new GetMethod("http://localhost/webservices/services/custommag/customs/"+id);
		try {
			//执行HTTP方法			
			handleHttpMethod(get);
			//获得GET方法,返回的结果
			String res = get.getResponseBodyAsString();
			System.out.println(res);
			if(!StringUtils.isEmpty(res)) {
				//转换成JAVA对象
				System.out.println(JAXBTool.xml2Java(CustomBean.class, res));
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	
		
	@Test
	public void updateCustomBean() {
		PutMethod put = new PutMethod("http://localhost/webservices/services/custommag/customs/"+id);
		//定义提交数据
		CustomBean custom = new CustomBean();
		custom.setCustomerName("李四");
		custom.setLoginName("ls");
		custom.setAge(18);
		custom.setGender(1);
		custom.setPassword("123456");
		
		try {
			String str = JAXBTool.java2Xml(CustomBean.class, custom);
			//将XML格式的字符串,转换成RequestEntity对象
			RequestEntity requestEntity = new InputStreamRequestEntity(new ByteArrayInputStream(str.getBytes("UTF-8")));
			put.setRequestEntity(requestEntity);
			put.setRequestHeader("Content-Type", "application/xml;charset=utf-8");
			//执行HTTP方法			
			handleHttpMethod(put);
			
			String res = put.getResponseBodyAsString();
			//获得PUT方法,返回的结果/
			//转换成JAVA对象
			System.out.println(JAXBTool.xml2Java(ResMessage.class, res));
			
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
		
	}
	
	
	@Test
	public void saveCustomBean() {
		PostMethod post = new PostMethod("http://localhost:8080/webservices/services/custommag/customs/0");
		//定义提交数据
		CustomBean custom = new CustomBean();
		custom.setCustomerName("张三");
		custom.setLoginName("zs");
		custom.setAge(18);
		custom.setGender(1);
		custom.setPassword("123456");
		
		try {
			String str = JAXBTool.java2Xml(CustomBean.class, custom);
			//将XML格式的字符串,转换成RequestEntity对象
			RequestEntity requestEntity = new InputStreamRequestEntity(new ByteArrayInputStream(str.getBytes("UTF-8")));
			post.setRequestEntity(requestEntity);
			post.setRequestHeader("Content-Type", "application/xml;charset=utf-8");
			//执行HTTP方法			
			handleHttpMethod(post);
			
			String res = post.getResponseBodyAsString();
			//获得POST方法,返回的结果
			System.out.println(res);
			
			//转换成JAVA对象
//			System.out.println(JAXBTool.xml2Java(ResMessage.class, res));
			
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
	}
	

	private void handleHttpMethod(HttpMethod method) {
		// TODO Auto-generated method stub
		HttpClient client = new HttpClient();
		int statusCode = 0;
		
		try {
			
			//设置请求头,指定传过去的消息是格式是xml,编码是utf-8
			method.setRequestHeader("Accept", "application/xml;charset=utf-8");
			
			//执行HTTP方法,并返回响应码
			statusCode = client.executeMethod(method);
			
			//根据返回的状态码,转换对应的状态枚举
			Response.Status status = Response.Status.fromStatusCode(statusCode);
			if(status == Response.Status.OK) {
				System.out.println("后台处理完毕!");
			}else if(status == Response.Status.NOT_FOUND) {
				System.out.println("请求路径错误!");
			}else if(status == Response.Status.METHOD_NOT_ALLOWED) {
				System.out.println("请求方法不被允许!");
			}
			
//			……
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
}

猜你喜欢

转载自blog.csdn.net/IT_CREATE/article/details/86642980