我收到了如下 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
<HERE COMES THE JPEG DATA>
试图存储它,最终结果是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 的偏移量。那么如何跳过标题并写入 jpeg 呢?
我不建议这样做*,但如果您确实喜欢以低级方式执行此操作,则 HTTP 标头部分始终以字符序列结尾"\r\n\r\n"
(\r\n
在规范中称为 CRLF)。如有疑问,请阅读HTTP 1.1 规范 http://www.w3.org/Protocols/rfc2616/rfc2616.html.
您需要做的就是搜索此模式:
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。只需最少的设置和配置,它的启动速度非常快。这可能听起来有些过分,但我认为从长远来看,你可以为自己节省一些痛苦。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)