我收到了如下 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 剥离 header ,然后读取剩余的(包含 jpeg 的)InputStream,但我猜 BufferedReader 不会影响 InputStream 的偏移量。那么如何跳过标题并编写 jpeg 呢?
最佳答案
我不建议这样做*,但如果您真的喜欢低级方式,HTTP header 部分总是以字符序列 "\r\n\r\n "
(\r\n
在规范中称为 CRLF)。如有疑问,请阅读 HTTP 1.1 specification .
您需要做的就是搜索此模式:
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。通过最少的设置和配置,它启动非常快。这听起来可能有些矫枉过正,但我认为从长远来看,您可以避免一些痛苦。
关于java - Http PUT 请求到 jpeg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20894603/