Http PUT请求jpeg

我收到了HTTP PUT,如:

PUT /photo HTTP/1.1 X-Apple-AssetKey: F92F9B91-954E-4D63-BB9A-EEC771ADE6E8 X-Apple-Transition: Dissolve Content-Length: 462848 User-Agent: MediaControl/1.0 X-Apple-Session-ID: 1bd6ceeb-fffd-456c-a09c-996053a7a08c  

试图存储它,最终在im==null exception

 Socket s = server.accept(); BufferedReader br = new BufferedReader(new InputStreamReader( s.getInputStream())); String tag = br.readLine().split(" ")[1]; System.out.println(tag); if (tag.contains("/photo")) { while (!br.readLine().equals("")); File file = new File("" + System.currentTimeMillis() + ".jpg"); InputStream is = (s.getInputStream()); BufferedImage bImageFromConvert = ImageIO.read(is); ImageIO.write(bImageFromConvert, "jpg", file); System.out.println(file); } br.close(); s.close(); 

所以我的想法是用BufferedReader剥离标题,然后读取剩余的(包含jpeg)InputStream,但我想BufferedReader不会影响InputStream的偏移量。 那么如何跳过Header并编写jpeg呢?

我不建议这样做*,但如果你真的喜欢低级方式,HTTP标题部分总是以字符序列"\r\n\r\n"\r\n在规范中被称为CRLF。 无论何时有疑问,请阅读HTTP 1.1规范 。

您需要做的就是搜索此模式:

 byte[] endOfHeader = "\r\n\r\n".getBytes(); // alt: getBytes(Charset.forName("ASCII")) int endIndex = 0; BufferedInputStream input = new BufferedInputStream(s.getInputStream()); input mark(); try { int read; while ((read = input.read()) != -1) { if (the last four bytes match endOfHeader) { // Left as an exercise ;-) break; } endIndex++; } } finally { input.reset(); } // Now you have the end of header in endIndex // You now have to re-read the header part using a character Reader // (BufferedReader is fine, just make sure you have the correct encoding) // but make sure read *exactly* until endIndex before attempting to read further. // The rest of input can now be read using ImageIO or similar, as you like. // PS: Don't forget that the content may be chunked or zipped during // transfer-encoding. You might need to handle this, unless you also // control the client sending the PUT request. // PPS: I told you wouldn't recommend this ;-) 

*)我首选的方法是使用嵌入式Jetty实例,并创建servlet来处理PUT。 通过最少的设置和配置,它启动非常快。 听起来有点矫枉过正,但我​​认为,从长远来看,你可以省去一些痛苦。