Http PUT请求jpeg

时间:2014-01-03 00:45:10

标签: java http 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

<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的偏移量。那么如何跳过Header并编写jpeg呢?

1 个答案:

答案 0 :(得分:0)

我不建议这样做*,但如果您真的喜欢以低级方式执行,那么HTTP标头部分始终以字符序列"\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。通过最少的设置和配置,它启动非常快。听起来有点矫枉过正,但我​​认为,从长远来看,你可以省去一些痛苦。