本文包括apache cxf rest的基本例子,文件上传,form提交和json提交。
IBookService.java
package com.unei.service; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.MatrixParam; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; /** * basic examples * @author Administrator */ @Path("/book") public interface IBookService { @GET public Response getBooks(); /** * @PathParam 测试 * @param id * @return */ @GET @Path("/id/{id}") public Response getBook(@PathParam("id")int id); /** * @QueryParam 测试 * url:http://localhost:9000/rest/book/page?from=1&to=10&order=sadf * @param from * @param to * @return */ @GET @Path("/page") public Response getBookById( @QueryParam("from")int from, @QueryParam("to")int to, @QueryParam("order")List<String> order); /** * @MatrixParam 测试 * url:http://localhost:9000/rest/book/matrix/2013;author=tom;country=china * @param year * @param author * @param country * @return */ @GET @Path("/matrix/{year}") public Response getBookByMatrix(@PathParam("year")String year, @MatrixParam("author")String author, @MatrixParam("country")String country); /** * @HeaderParam 测试 * 获取http头信息 * url:http://localhost:9000/rest/book/getHeader * @param userAgent * @return */ @GET @Path("/getHeader") public Response getHeader(@HeaderParam("user-agent")String userAgent); }
BookService.java
package com.unei.service.impl; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import org.apache.cxf.jaxrs.ext.multipart.Attachment; import com.unei.service.IBookService; public class BookService implements IBookService{ @Override public Response getBooks() { System.out.println("getBooks is called..."); return Response.ok().entity("").build(); } @Override public Response getBook(int id) { System.out.println("getBook is called..."); return Response.ok().entity(id).build(); } @Override public Response getBookById(int from , int to,List<String> order){ System.out.println("getBookById is called..."); return Response.ok().entity("from "+from+" to "+to+" order by "+order.toString()).build(); } @Override public Response getBookByMatrix(String year, String author, String country) { System.out.println("getBookByMatrix is called..."); return Response.ok().entity("year:"+year+",author:"+author+",country:"+country).build(); } @Override public Response getHeader(String userAgent) { System.out.println("getHeader is called..."); return Response.ok().entity(userAgent).build(); } }
启动服务器(Server.java)后,在浏览器中输入代码注释中的url。
IUploadService.java
package com.unei.service; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import org.apache.cxf.jaxrs.ext.multipart.Attachment; import org.apache.cxf.jaxrs.ext.multipart.Multipart; /** * 文件上传service * @author Administrator * */ @Path("/upload") public interface IUploadService { /** * 文本文档下载 * url:http://localhost:9000/rest/upload/dlText * @return */ @GET @Path("dlText") @Produces("text/plain") public Response downloadText(); /** * 表单提交,文件上传 * @return */ @POST @Path("/upload") @Consumes("multipart/form-data") public Response uploadFileByForm( @Multipart(value="id",type="text/plain")String id, @Multipart(value="name",type="text/plain")String name, @Multipart(value="file",type="image/png")Attachment image); /** * 多文件上传 * @param attchments * @param request * @return */ @POST @Path("/uploadlist") @Consumes("multipart/form-data") public Response uploadFileList(List<Attachment>attachments,@Context HttpServletRequest request); }
UploadService.java
注意一下代码中对流的处理(代码中处理是错误的,~~)
try{}finally{
//关闭流
}
package com.unei.service.impl; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.activation.DataHandler; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import org.apache.cxf.jaxrs.ext.multipart.Attachment; import com.unei.service.IUploadService; public class UploadService implements IUploadService { @Override public Response downloadText() { File file = new File("D:\\test.txt"); ResponseBuilder response = Response.ok(file); response.header("Content-Disposition", "attachment;filename='test.txt'"); return response.build(); } @Override public Response uploadFileByForm(String id, String name, Attachment image) { System.out.println("id:" + id); System.out.println("name:" + name); DataHandler dh = image.getDataHandler(); try { InputStream ins = dh.getInputStream(); writeToFile(ins, "D:\\upload\\" + dh.getName()); } catch (Exception e) { e.printStackTrace(); } return Response.ok().entity("ok").build(); } @Override public Response uploadFileList(List<Attachment> attachments, HttpServletRequest request) { if (attachments.size() > 0) System.out.println("ok"); for (Attachment attach : attachments) { DataHandler dh = attach.getDataHandler(); System.out.println(attach.getContentType().toString()); if (attach.getContentType().toString().equals("text/plain")) { try { System.out.println(dh.getName()); System.out.println(writeToString(dh.getInputStream())); } catch (Exception e) { e.printStackTrace(); } } else { try { writeToFile(dh.getInputStream(), "D:\\upload\\" + dh.getName()); } catch (IOException e) { e.printStackTrace(); } } } return Response.ok().entity("ok").build(); } private void writeToFile(InputStream ins, String path) { try { OutputStream out = new FileOutputStream(new File(path)); int read = 0; byte[] bytes = new byte[1024]; while ((read = ins.read(bytes)) != -1) { out.write(bytes, 0, read); } out.flush(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private String writeToString(InputStream ins) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] b = new byte[1024]; int i = -1; while ((i = ins.read(b)) != -1) { out.write(b, 0, i); } ins.close(); return new String(out.toByteArray(), "UTF-8"); } }
测试使用两种方法,一种使用html页面,另一种使用HttpClient测试。
uploadFileByForm.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <form action="http://localhost:9000/rest/upload/upload" method="post" enctype="multipart/form-data" > <p>id:<input type="text" name="id"/></p> <p>name:<input type="text" name="name"/></p> <p>image:<input type="file" name="file"/> <p><input type="submit" value="sub"/></p> </form> </body> </html>uploadFileList.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <form action="http://localhost:9000/rest/upload/uploadlist" method="post" enctype="multipart/form-data" > <p>id:<input type="text" name="id"/></p> <p>name:<input type="text" name="name"/></p> <p>image:<input type="file" name="file"/></p> <p>image2:<input type="file" name="file2"/></p> <p><input type="submit" value="sub"/></p> </form> </body> </html>
启动服务器后(server.java),提交表单
package com.unei.app; import java.io.File; import java.nio.charset.Charset; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; public class Client { public static void main(String[] args) throws Exception { MultipartEntity entity=new MultipartEntity(); entity.addPart("id",new StringBody("newid", Charset.forName("UTF-8"))); entity.addPart("name",new StringBody("newName",Charset.forName("UTF-8"))); entity.addPart("file1",new FileBody(new File("D:\\test.txt"))); HttpPost request=new HttpPost("http://localhost:9000/rest/upload/uploadlist"); request.setEntity(entity); HttpClient client=new DefaultHttpClient(); client.execute(request); } }
package com.unei.bean; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "book") public class Book { private int bookId; private String bookName; public int getBookId() { return bookId; } public void setBookId(int bookId) { this.bookId = bookId; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public String toString(){ return "[bookId:"+bookId+"],[bookName:"+bookName+"]"; } }
package com.unei.service; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.Response; import com.unei.bean.Book; @Path("/json") public interface IJsonService { /** * JSON提交 * url:http://localhost:9000/rest/json/addBook * Json format:{"book":{"bookId":123,"bookName":"newBook"}} * @param book * @return */ @POST @Path("/addBook") @Consumes("application/json") public Response addBook(Book book); /** * Json提交2 * url:http://localhost:9000/rest/json/addBooks * Json format:{"book":[{"bookId":123,"bookName":"newBook"},{"bookId":456,"bookName":"newBook2"}]} * @param books * @return */ @POST @Path("/addBooks") @Consumes("application/json") public Response addBooks(List<Book> books); }
package com.unei.service.impl; import java.util.List; import javax.ws.rs.core.Response; import com.unei.bean.Book; import com.unei.service.IJsonService; public class JsonService implements IJsonService{ @Override public Response addBook(Book book) { System.out.println("addBook is called..."); return Response.ok().entity(book.toString()).build(); } @Override public Response addBooks(List<Book> books) { System.out.println("addBooks is called..."); return Response.ok().entity("ok").build(); } }
package com.unei.app; import java.util.ArrayList; import java.util.List; import org.apache.cxf.jaxrs.JAXRSServerFactoryBean; import org.apache.cxf.jaxrs.lifecycle.ResourceProvider; import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider; import com.unei.service.impl.BookService; import com.unei.service.impl.JsonService; import com.unei.service.impl.UploadService; public class Server { @SuppressWarnings({ "unchecked", "rawtypes" }) public Server() { JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean(); List clazzs=new ArrayList(); clazzs.add(BookService.class); clazzs.add(UploadService.class); clazzs.add(JsonService.class); sf.setResourceClasses(clazzs); List<ResourceProvider> rps=new ArrayList<ResourceProvider>(); for(int i=0;i<clazzs.size();i++) rps.add(new SingletonResourceProvider(clazzs.get(i))); sf.setResourceProviders(rps); // sf.getInInterceptors().add(new LoggingInInterceptor()); // sf.getOutInterceptors().add(new LoggingOutInterceptor()); sf.setAddress("http://localhost:9000/rest"); 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 existing"); System.exit(0); } }