今天简单介绍一下如何用Java支持HTTP Multipart的request和response。 整个项目的代码可以在https://github.com/mcai4gl2/multi下载。
在这个程序里,我们的业务场景很简单。在服务端有一个随机数生成器,可以生成随机的Integer和Guid,客户端通过服务,可以请求一个或多个随机数。同时,客户端可以向服务端发送一个或多个随机数,这些随机数会被加入到一个队列中,被其他的客户端通过请求获得。以下是我们的随机数Bean的定义:
[java] view plaincopy
- public class RandNumber {
- private String uuid;
- private Integer number;
- public String getUuid() {
- return uuid;
- }
- public void setUuid(String uuid) {
- this.uuid = uuid;
- }
- public Integer getNumber() {
- return number;
- }
- public void setNumber(Integer number) {
- this.number = number;
- }
- @Override
- public String toString() {
- return number + " " + uuid;
- }
- public static class Builder {
- private RandNumber number;
- public Builder() {
- number = new RandNumber();
- }
- public Builder randomlyGenerate() {
- Random random = new Random();
- number.setNumber(random.nextInt(100));
- number.setUuid(UUID.randomUUID().toString());
- return this;
- }
- public Builder withNumber(int num) {
- number.setNumber(num);
- return this;
- }
- public Builder withUuid(String uuid) {
- number.setUuid(uuid);
- return this;
- }
- public RandNumber build() {
- return number;
- }
- }
- }
在这个类中,我们除了定义类的基本信息,还添加了一个Builder类。通过这个Builder类,我们可以很方便的生成RandNumber类。Builder类在我们的数据类的Constructor很复杂的时候,非常有用,可以使我们的代码更具可读性。
有了这个简单的数据类,我们继续定义一个简单的业务类RandomNumberGenerator,它继承了IRandomNumberGenerator接口:
[java] view plaincopy
- public interface IRandomNumberGenerator {
- RandNumber getRandomNumber();
- RandNumber[] getRandomNumbers(int num);
- void submitRandomNumber(RandNumber randNumber);
- void submitRandomNumbers(RandNumber[] randNumbers);
- }
同时,我们还定义了一个RandomNumberSerializer类,它可以对我们的数据类进行JSON Serialization操作,我们的服务端和客户端都将使用它进行通信:
[java] view plaincopy
- public interface IRandomNumberSerializer {
- String serializeRandomNumber(RandNumber number);
- RandNumber deserializeRandomNumber(String input);
- void serializeRandomNumber(RandNumber number, OutputStream stream);
- RandNumber deserializeRandomNumber(InputStream stream);
- String getContentType();
- }
RandomNumberSerializer内部使用了Gson包来进行序列化操作。在上面的接口中,我们提供了对String和Stream的两种方法,这样,当我们进行HTTP通信的时候,我们可以直接对Network Stream进行操作。
有了上面的这些类,我们的Servlet服务端代码就很简单了:
[java] view plaincopy
- @Controller
- public class MultiPartRequestServlet {
- private static Logger log = Logger.getLogger(MultiPartRequestServlet.class);
- @Autowired
- private IRandomNumberSerializer randomNumberSerializer;
- @Autowired
- private IRandomNumberGenerator randomNumberGenerator;
- @RequestMapping(value="/get-multi", method = RequestMethod.GET)
- public void getMultiple(
- @RequestHeader("MAX_NUM_NUMS") int maxCount,
- HttpServletRequest request,
- HttpServletResponse response,
- ServletOutputStream outputStream) throws Exception {
- log.info("multi part get is called");
- response.setStatus(HttpServletResponse.SC_OK);
- String boundary = UUID.randomUUID().toString();
- response.setContentType("multipart/x-mixed-replace;boundary=" + boundary);
- RandNumber[] numbers = randomNumberGenerator.getRandomNumbers(maxCount);
- for (int index = 0; index < maxCount; index++) {
- outputStream.println("--" + boundary);
- outputStream.println("Content-Type: " + randomNumberSerializer.getContentType());
- outputStream.println();
- outputStream.println(randomNumberSerializer.serializeRandomNumber(numbers[index]));
- outputStream.println();
- }
- outputStream.println("--" + boundary + "--");
- outputStream.flush();
- outputStream.close();
- }
- @RequestMapping(value="/submit-multi", method = RequestMethod.POST)
- public void submitMultiple(HttpServletRequest request, HttpServletResponse response) throws Exception {
- log.info("multi part submit is called");
- if (!request.getContentType().startsWith("multipart/form-data")) {
- response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
- } else {
- request.setAttribute("org.eclipse.multipartConfig",
- new MultipartConfigElement(System.getProperty("java.io.tmpdir")));
- Collection<Part> parts = request.getParts();
- for (Part part : parts) {
- RandNumber number = randomNumberSerializer.deserializeRandomNumber(part.getInputStream());
- randomNumberGenerator.submitRandomNumber(number);
- }
- response.setStatus(HttpServletResponse.SC_OK);
- }
- }
- @RequestMapping(value="/get-one", method = RequestMethod.GET)
- public void getOne(HttpServletRequest request, HttpServletResponse response, OutputStream outputStream) throws Exception {
- log.info("get is called");
- RandNumber number = randomNumberGenerator.getRandomNumber();
- response.setStatus(HttpServletResponse.SC_OK);
- response.setContentType(randomNumberSerializer.getContentType());
- randomNumberSerializer.serializeRandomNumber(number, outputStream);
- outputStream.flush();
- outputStream.close();
- }
- @RequestMapping(value="/submit-one", method = RequestMethod.POST)
- public void submitOne(HttpServletRequest request, HttpServletResponse response) throws Exception {
- log.info("submit is called");
- RandNumber number = randomNumberSerializer.deserializeRandomNumber(request.getInputStream());
- randomNumberGenerator.submitRandomNumber(number);
- response.setStatus(HttpServletResponse.SC_OK);
- }
- }
在上面的代码中,getOne和submitOne很简单,这里我们主要讨论getMultiple和submitMultiple。在getMultiple中,我们直接操作outputStream来实现Multipart协议。而在submitMultiple中,我们则通过Servlet 3.0的getParts方法来直接获得每一个Part。需要注意的是,getParts是在Servlet 3.0中才新添加的方法,在我们部署服务的时候,我们要部署在支持Servlet 3.0的container里(在这里我对Tomcat7和Jetty8进行了测试)。同时,我们在调用getParts之前,我们对request添加了一个attribute,这个attribute只在部署在Jetty时需要。
下面的代码是一个简单的getMultiple的客户端,在这段代码中,我们使用Apache HttpClient来进行HTTP,我们使用了java mail中的MimeMultipart来处理服务端的repsonse。
[java] view plaincopy
- @Override
- public RandNumber[] getRandomNumbers(int num) {
- HttpGet httpGet = new HttpGet(getMultipleUrl);
- httpGet.setHeader("MAX_NUM_NUMS", Integer.toString(num));
- try {
- HttpResponse httpResponse = httpClient.execute(httpGet);
- if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
- ByteArrayDataSource source = new ByteArrayDataSource(httpResponse.getEntity().getContent(),
- "multipart/mixed");
- MimeMultipart multipart = new MimeMultipart(source);
- List<RandNumber> numbers = new ArrayList<RandNumber>();
- for (int index = 0; index < multipart.getCount(); index++) {
- numbers.add(randomNumberSerializer.deserializeRandomNumber(multipart.getBodyPart(index).getInputStream()));
- }
- return numbers.toArray(new RandNumber[numbers.size()]);
- } else {
- HttpEntity httpDataEntity = httpResponse.getEntity();
- EntityUtils.consumeQuietly(httpDataEntity);
- return null;
- }
- } catch (Exception ex) {
- log.error("Failed to get multiple random numbers", ex);
- return null;
- }
- }
除了代码,我还添加了Maven打包配置和发布到local tomcat的脚本。整个Maven项目会被打包成两个文件,一个JAR和一个WAR。JAR打包包含了一个Jetty的服务端程序入口,和一个SampleClient的程序入口。而另一个WAR包可以直接发布到Tomcat上进行调试。这些都是为了我们可以更方便的在本地进行代码调试,在tomcat的启动脚本中,我还打开了JPDA端口,这样我们可以通过IDE对部署在Tomcat上的服务端进行调试。
这些基本的配置,可以大大提高我们编程调试的效率。这也是我写这篇文章的另一个原因。希望这些配置,可以帮到有需要的朋友。
原文:http://blog.csdn.net/mcai4gl2/article/details/12354945