WebService专题(八)-CXF发布REST服务

1.什么是REST

  • 定义:REST就是一种编程风格,它可以精确定位网上资源(服务接口、方法、参数)
    REST支持数据格式:XML、JSON
    REST支持发送方式:GET,POS

2.CXF+Spring整合REST服务

2.1.需求

第一个:查询单个学生
第二个:查询多个学生

2.2.实现

2.2.1.服务端
  • 导入依赖
<!-- 集中定义依赖版本号 -->
  <properties>

    <junit.version>4.12</junit.version>
    <cxf.version>3.2.6</cxf.version>

  </properties>

  <dependencies>

    <!-- 单元测试 -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-core</artifactId>
      <version>${cxf.version}</version>
    </dependency>

    <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-frontend-jaxws</artifactId>
      <version>3.2.6</version>
    </dependency>
    
    <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-transports-http</artifactId>
      <version>3.2.6</version>
    </dependency>


  </dependencies>

2.创建学生类,需要加入@ XmlRootElement

@XmlRootElement(name="student")//@XmlRootElement可以实现对象和XML数据之间的转换
public class Student {

	private long id;
	private String name;
	private Date birthday;

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
}

3.创建SEI接口

@WebService
@Path("/student")//@Path("/student")就是将请求路径中的“/student”映射到接口上
public interface StudentInterface {

	   /**
	    * 根据id查询单个学生
	    * @param id
	    * @return
	    */
	    @GET  //指定请求方式,如果服务端发布的时候指定的是GET(POST),那么客户端访问时必须使用GET(POST)
	    @Produces(MediaType.APPLICATION_XML_VALUE)//指定服务数据类型
	    @Path("/query/{id}")//@Path("/query/{id}")就是将"/query"映射到方法上,"{id}"映射到参数上,多个参数,以“/”隔开,放到“{}”中
		public Student queryStuById(@PathParam("id")long id);
		
	    /**
		 * 根据查询多个学生
		 * @param name
		 * @return
		 */
	    @GET
	    @Produces({MediaType.APPLICATION_XML_VALUE,"application/json;charset=utf-8"})
	    @Path("/querylist/{name}")
		public List<Student> queryStudentList(@PathParam("name") String name);
}

4.创建SEI接口实现类

public class StudentInterfaceImpl implements StudentInterface {

	@Override
	public Student queryStuById(long id) {
		Student st = new Student();
		st.setId(id);
		st.setName("张三");
		st.setBirthday(new Date());
		return st;
	}

	@Override
	public List<Student> queryStudentList(String name) {
		Student st = new Student();
		st.setId(110);
		st.setName("张三");
		st.setBirthday(new Date());

		Student st2 = new Student();
		st2.setId(120);
		st2.setName("李四");
		st2.setBirthday(new Date());

		List<Student> list = new ArrayList<Student>();
		list.add(st);
		list.add(st2);
		return list;
	}
}

5.发布服务

public class StudentServer {

	public static void main(String[] args) {
		// JAXRSServerFactoryBean发布REST的服务
		JAXRSServerFactoryBean factoryBean = new JAXRSServerFactoryBean();
		// 设置服务实现类
		factoryBean.setServiceBean(new StudentInterfaceImpl());
		// 设置资源类,如果有多个资源类,可以以“,”隔开。
		factoryBean.setResourceClasses(StudentInterfaceImpl.class);
		// 设置服务地址
		factoryBean.setAddress("http://localhost:8888/user");
		// 发布服务
		factoryBean.create();
		System.out.println("服务已经发布.....");
	}
}

6.测试服务
测试查询单个学生:http://localhost:8888/user/student/query/1002
结果如下:

 <student>
          <birthday>2017-11-19T21:39:18.449+08:00</birthday>
          <id>1002</id>
          <name>张三</name>
 </student>

测试查询多个学生:http://localhost:8888/user/student/querylist/1002
GET请求默认是xml类型:
结果如下:

<students>
      <student>
              <birthday>2017-11-19T21:40:16.609+08:00</birthday>
              <id>110</id>
              <name>张三</name>
        </student>
        <student>
              <birthday>2017-11-19T21:40:16.609+08:00</birthday>
              <id>120</id>
              <name>李四</name>
        </student>
</students>

多个类型选择:http://localhost:8888/user/student/querylist/1002?_type=json
结果如下:

{"student":
	[
	{"birthday":"2017-11-19T21:41:28.204+08:00","id":110,"name":"张三"},	
	{"birthday":"2017-11-19T21:41:28.204+08:00","id":120,"name":"李四"}
	]
}

备注:

如果服务端发布时指定请求方式是GET(POST),客户端必须使用GET(POST)访问服务端,否则会报异常
如果在同一方法上同时指定XML和JSON媒体类型,默认返回XML

2.2.2.客户端
public class HttpClient {

	public static void main(String[] args) throws Exception {
		System.out.println("haha");
		// 第一步:创建服务地址,不是WSDL地址
		URL url = new URL("http://localhost:8888/user/student/querylist/1002?_type=json");
		// 第二步:打开一个通向服务地址的连接
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		// 第三步:设置参数
		// 3.1发送方式设置:POST必须大写
		connection.setRequestMethod("GET");
		// Post 请求不能使用缓存
		connection.setUseCaches(false);
		connection.setInstanceFollowRedirects(true);
		// 3.2设置数据格式:content-type
		// 3.3设置输入输出,因为默认新创建的connection没有读写权限,
		connection.setDoInput(true);
		connection.setDoOutput(true);
		// 第五步:接收服务端响应,打印
		int responseCode = connection.getResponseCode();
		if (200 == responseCode) {// 表示服务端响应成功
			InputStream is = connection.getInputStream();
			InputStreamReader isr = new InputStreamReader(is,"UTF-8");
			BufferedReader br = new BufferedReader(isr);

			StringBuilder sb = new StringBuilder();
			String temp = null;
			while (null != (temp = br.readLine())) {
				sb.append(temp);
			}
			System.out.println(sb.toString());
			// dom4j解析返回数据,课下作业
			is.close();
			isr.close();
			br.close();
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

熊猫-IT

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值