一、嵌入式运行Jetty并提供上传文件功能
1、定义处理请求的Handler
public class DispatchRequestHandler extends AbstractHandler { public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8"); response.setHeader("Cache-Control", "no-cache"); response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); if(target.contains("/upload")){//process file upload processUploadFileRequest(request, response); }else{//other request response.getWriter().println("<h1>Hello World</h1>"); response.getWriter().println("<li>Request url: " + target + "</li>"); response.getWriter().println("<li>Server port: " + request.getServerPort() + "</li>"); } } private void processUploadFileRequest(HttpServletRequest request, HttpServletResponse response){ try{ String uploadPath = "D:/upload"; File uploadFolder = new File(uploadPath); if(!uploadFolder.exists()){ uploadFolder.mkdirs(); } boolean isMultipart = ServletFileUpload.isMultipartContent(request); if(!isMultipart){ throw new Exception("not file upload request!"); } DiskFileItemFactory factory = new DiskFileItemFactory(); //factory.setSizeThreshold(4094); //factory.setRepository(new File("D:/temp/buffer")); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(10*1024*1024); FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { System.out.println("Form field " + name + " with value " + Streams.asString(stream) + " detected."); } else { System.out.println("File field " + name + " with file name " + item.getName() + " detected."); File savedFile = new File(uploadPath, item.getName()); FileOutputStream fos = new FileOutputStream(savedFile); byte[] buff = new byte[1024]; int len = 0; while((len = stream.read(buff)) > 0){ fos.write(buff, 0, len); } fos.close(); } } /* List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> it = items.iterator(); while(it.hasNext()){ FileItem item = (FileItem)it.next(); if(item.isFormField()){ System.out.print(item.getFieldName()+"="+item.getString()); }else{ String fileName = item.getName(); //item.getInputStream(); System.out.println(fileName); if(fileName != null){ File savedFile = new File(uploadPath, fileName); item.write(savedFile); } } } */ response.getWriter().println("1");//success }catch(Exception e){ e.printStackTrace(); try{ response.getWriter().println("0");//fail }catch(Exception ex){} } } }
2、嵌入式运行Jetty
public class MainEntrance { public static void main(String[] args){ Server server = new Server();//jetty server SelectChannelConnector connector_1 = new SelectChannelConnector(); connector_1.setPort(8088); SelectChannelConnector connector_2 = new SelectChannelConnector(); connector_2.setPort(8089); server.setConnectors(new Connector[]{connector_1,connector_2}); server.setHandler(new DispatchRequestHandler()); try { server.start(); } catch (Exception e) { e.printStackTrace(); } } }
3、用HttpClient上传文件进行测试
public class TestUpload { public static void main(String[] args) { String targetURL = "http://127.0.0.1:8088/upload"; File uploadFile = new File("D:/test/IMG_5352.JPG"); HttpClient httpClient = new DefaultHttpClient();//apache httpClient HttpPost httpPost = new HttpPost(targetURL); try { FileBody fileBody = new FileBody(uploadFile); StringBody comment = new StringBody("测试上传文件",Charset.forName("UTF-8")); MultipartEntity multipartEntity = new MultipartEntity(); multipartEntity.addPart("upload", fileBody); multipartEntity.addPart("comment", comment); httpPost.setEntity(multipartEntity); HttpResponse response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); if(statusCode == HttpStatus.SC_OK){ HttpEntity resEntity = response.getEntity(); System.out.println(EntityUtils.toString(resEntity)); } } catch (Exception e) { e.printStackTrace(); } finally { try { httpClient.getConnectionManager().shutdown(); } catch (Exception ignore) { } } } }
二、JDK6自带的HttpServer
1.Server端
public class JDK6HTTPServer { public static void run(){ try{ HttpServerProvider provider = HttpServerProvider.provider(); HttpServer httpServer = provider.createHttpServer(new InetSocketAddress(80),100);//concurrent request 100 httpServer.createContext("/", new JDK6HTTPServer().new JDK6HTTPServerHandler()); httpServer.setExecutor(null);//creates a default executor httpServer.start(); System.out.println("JDK6HTTPServer started..."); }catch(Exception e){ } } public class JDK6HTTPServerHandler implements HttpHandler{ public void handle(HttpExchange httpExchange) throws IOException { //System.out.println(httpExchange.getRequestURI()); InputStream inputStrean = httpExchange.getRequestBody(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStrean)); String temp = null; while((temp = reader.readLine()) != null){ System.out.println("client request:"+temp); } StringBuffer buff = new StringBuffer(); buff.append("<h1>Hello World</h1>"); httpExchange.sendResponseHeaders(200, buff.toString().getBytes().length); OutputStream outputStream = httpExchange.getResponseBody(); outputStream.write(buff.toString().getBytes()); outputStream.close(); } } public static void main(String[] args){ run(); } }
2.client端测试
public class TestJDK6HTTPServer { public static void requestServer(){ try{ URL url = new URL("http://127.0.0.1"); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); urlConn.setDoOutput(true); urlConn.setDoInput(true); urlConn.setRequestMethod("POST"); String msg = "测试内容"; OutputStream out = urlConn.getOutputStream(); out.write(msg.getBytes()); out.flush(); if(urlConn.getContentLength() != -1 && urlConn.getResponseCode() == 200) { InputStream in = urlConn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String temp = ""; while ((temp = reader.readLine()) != null) { System.err.println("server response:" + temp); } reader.close(); in.close(); urlConn.disconnect(); } }catch(Exception e){ e.printStackTrace(); } } public static void main(String[] args){ ExecutorService exec = Executors.newCachedThreadPool(); for (int i = 0; i < 20; i++) { Runnable run = new Runnable() { public void run() { requestServer(); } }; exec.execute(run); } exec.shutdown(); } }