浏览 6590 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2009-03-03
/** * * @author rikugun */ public class Main { public static void main(String[] args) { try { HttpServer hs = HttpServer.create(new InetSocketAddress(8888), 0);//设置HttpServer的端口为8888 hs.createContext("/pic", new PicHandler());//用PicHandler类内处理到/pic的请求 hs.setExecutor(null); // creates a default executor hs.start(); } catch (IOException e) { e.printStackTrace(); } } } PicHandler.java /** * * @author rikugun */ public class PicHandler implements HttpHandler { public void handle(HttpExchange t) throws IOException { String response = ""; String mt = t.getRequestMethod(); if (t.getRequestMethod().equals("GET")) { response = "<h3>请使用POST提交图片!</h3>"; } else { InputStream is = t.getRequestBody(); doUpload(is); response = "<h3>上传成功!</h3>"; } t.sendResponseHeaders(200, response.length()); OutputStream os = t.getResponseBody(); os.write(response.getBytes()); os.close(); } private void doUpload(InputStream is) { FileOutputStream fos = null; try { fos = new FileOutputStream(new File("out.txt")); } catch (FileNotFoundException ex) { Logger.getLogger(PicHandler.class.getName()).log(Level.SEVERE, null, ex); } byte b[] = new byte[8192]; int isEnd = 0; while (true) { try { isEnd = is.read(b); if (isEnd == -1) { //文件末尾 break; } System.out.println(b.toString()); fos.write(b); } catch (IOException ex) { ex.printStackTrace(); break; } } try { fos.close(); is.close(); } catch (IOException ex) { Logger.getLogger(PicHandler.class.getName()).log(Level.SEVERE, null, ex); } } } 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |