为什么80%的码农都做不了架构师?>>>
一、首先还是创建个项目并把包导入去,弄2个package,分别用于装server和client。记得要把commons-httpclient-3.1.jar也要放入来,因为Client用http请求的:
二、在com.yao.server下新建一个类Customer,我们注意到有一个@XmlRootElement(name="Customer")这个是用来标识Customer是可用来转化为xml的:
package com.yao.rs.server;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElement(name="Customer")
public class Customer {private long id;private String name;@Overridepublic String toString() {return "Customer [id=" + id + ", name=" + name + "]";}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;}}
package com.yao.rs.server;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElement(name="Product")
public class Product {private long id;private String description;public long getId() {return id;}public void setId(long id) {this.id = id;}public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}@Overridepublic String toString() {return "Product [id=" + id + ", description=" + description + "]";}}
package com.yao.rs.server;import java.util.HashMap;
import java.util.Map;import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;public class Order {private long id;private String description;private Map
package com.yao.rs.server;import java.util.HashMap;
import java.util.Map;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.Produces;
import javax.ws.rs.core.Response;@Path("/customerservice/")
@Produces("text/xml")//可以通过修改@Produces注解来声明暴露接口返回的json还是xml数据格式
public class CustomerService {long currentId = 123;Map
六、新建一个source folder名为config,在里面放置2个文件add_customer.xml和update_customer.xml用于客户端增加与更新的xml文件。如下为其代码:
6.1 add_customer.xml
6.2 update_customer.xml
七、新建Server启动类:
八、新建客户端类Client: package com.yao.rs.server;import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider;public class Server {protected Server() throws Exception {JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();sf.setResourceClasses(CustomerService.class);sf.setResourceProvider(CustomerService.class, new SingletonResourceProvider(new CustomerService()));sf.setAddress("http://localhost:9000/");sf.create();}public static void main(String args[]) throws Exception {new Server();System.out.println("Server ready...");Thread.sleep(5 * 6000 * 1000);System.out.println("Server exiting");System.exit(0);}
}
package com.yao.rs.client;import java.io.File;
import java.io.InputStream;
import java.net.URL;import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.FileRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.RequestEntity;import org.apache.cxf.helpers.IOUtils;
import org.apache.cxf.io.CachedOutputStream;
import org.apache.cxf.resource.URIResolver;public final class Client {private Client() {}public static void main(String args[]) throws Exception {// Sent HTTP GET request to query all customer info/** URL url = new URL("http://localhost:9000/customers");* System.out.println("Invoking server through HTTP GET to query all* customer info"); InputStream in = url.openStream(); StreamSource* source = new StreamSource(in); printSource(source);*/// Sent HTTP GET request to query customer infoSystem.out.println("Sent HTTP GET request to query customer info");URL url = new URL("http://localhost:9000/customerservice/customers/123");InputStream in = url.openStream();System.out.println(getStringFromInputStream(in));// Sent HTTP GET request to query sub resource product infoSystem.out.println("\n");System.out.println("Sent HTTP GET request to query sub resource product info");url = new URL("http://localhost:9000/customerservice/orders/223/products/323");in = url.openStream();System.out.println(getStringFromInputStream(in));// Sent HTTP PUT request to update customer infoSystem.out.println("\n");System.out.println("Sent HTTP PUT request to update customer info");Client client = new Client();String inputFile = client.getClass().getResource("/update_customer.xml").getFile();URIResolver resolver = new URIResolver(inputFile);File input = new File(resolver.getURI());PutMethod put = new PutMethod("http://localhost:9000/customerservice/customers");RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");put.setRequestEntity(entity);HttpClient httpclient = new HttpClient();try {int result = httpclient.executeMethod(put);System.out.println("Response status code: " + result);System.out.println("Response body: ");System.out.println(put.getResponseBodyAsString());} finally {// Release current connection to the connection pool once you are// doneput.releaseConnection();}// Sent HTTP POST request to add customerSystem.out.println("\n");System.out.println("Sent HTTP POST request to add customer");inputFile = client.getClass().getResource("/add_customer.xml").getFile();resolver = new URIResolver(inputFile);input = new File(resolver.getURI());PostMethod post = new PostMethod("http://localhost:9000/customerservice/customers");post.addRequestHeader("Accept" , "text/xml");entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");post.setRequestEntity(entity);httpclient = new HttpClient();try {int result = httpclient.executeMethod(post);System.out.println("Response status code: " + result);System.out.println("Response body: ");System.out.println(post.getResponseBodyAsString());} finally {// Release current connection to the connection pool once you are// donepost.releaseConnection();}System.out.println("\n");System.exit(0);}private static String getStringFromInputStream(InputStream in) throws Exception {CachedOutputStream bos = new CachedOutputStream();IOUtils.copy(in, bos);in.close();bos.close();return bos.getOut().toString();}}
2014-8-22 12:45:34 org.apache.cxf.endpoint.ServerImpl initDestination
信息: Setting the server's publish address to be http://localhost:9000/
2014-8-22 12:45:34 org.eclipse.jetty.server.Server doStart
信息: jetty-8.1.15.v20140411
2014-8-22 12:45:34 org.eclipse.jetty.server.AbstractConnector doStart
信息: Started SelectChannelConnector@localhost:9000
2014-8-22 12:45:35 org.apache.cxf.wsdl.service.factory.ReflectionServiceFactoryBean buildServiceFromWSDL
信息: Creating Service {http://docs.oasis-open.org/ws-dd/ns/discovery/2009/01}Discovery from WSDL: classpath:/org/apache/cxf/ws/discovery/wsdl/wsdd-discovery-1.1-wsdl-os.wsdl
2014-8-22 12:45:35 org.apache.cxf.endpoint.ServerImpl initDestination
信息: Setting the server's publish address to be soap.udp://239.255.255.250:3702
2014-8-22 12:45:35 org.apache.cxf.wsdl.service.factory.ReflectionServiceFactoryBean buildServiceFromClass
信息: Creating Service {http://docs.oasis-open.org/ws-dd/ns/discovery/2009/01}DiscoveryProxy from class org.apache.cxf.jaxws.support.DummyImpl
Server ready...
Sent HTTP GET request to query customer info
Response status code: 200
Response body: Sent HTTP POST request to add customer
Response status code: 200
Response body:
----invoking getCustomer, Customer id is: 123
----invoking getOrder, Order id is: 223
----invoking getProduct with id: 323
----invoking updateCustomer, Customer name is: Mary
----invoking addCustomer, Customer name is: Jack