Search code examples
javaziphttpresponsemultipartform-datamime

How to obtain just a single form field from an HttpResponse in Java and write it to a file?


I am calling a client's download service which sends back MIME data and attempting to save a zip file.

The service does not simply return the file by itself but several other MIME fields as well. So when I open the inputstream using entity.getContent() I end up writing all of this data to my zip file whereas I only wish to write one part "Payload". I have searched and do not see anyway to obtain just the one individual part from the content.

Code is below:

HttpResponse response = services.getFileByPayloadID("12345-abcde");

BufferedInputStream bis = null;
try {
    bis = new BufferedInputStream(response.getEntity().getContent());
} catch (UnsupportedOperationException | IOException e) {
    e.printStackTrace();
}
String filePath = "c:\\sample.zip";
BufferedOutputStream bos = null;
try {
    bos = new BufferedOutputStream(new FileOutputStream(new File(filePath)));

    int inByte;

    while((inByte = bis.read()) != -1) {
        bos.write(inByte);
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {bis.close();} catch (Exception e) {}
    try {bos.close();} catch (Exception e) {}
}

Contents of the file that is produced are shown below. Note that I only wish to write the actual binary content for "Payload" to the file. Any pointers or suggestions would be greatly appreciated!

----20170803161934 Content-Disposition: form-data;name="PayloadType"

X12_999_Response_005010X231A1 ----20170803161934 Content-Disposition: form-data;name="ProcessingMode"

Batch ----20170803161934 Content-Disposition: form-data;name="PayloadID"

12345-abcde ----20170803161934 Content-Disposition: form-data;name="TimeStamp"

2017-08-08T16:46:34Z ----20170803161934 Content-Disposition: form-data;name="CORERuleVersion"

2.2.0 ----20170803161934 Content-Disposition: form-data;name="ReceiverID"

99000061 ----20170803161934 Content-Disposition: form-data;name="SenderID"

KYMEDICAID ----20170803161934 Content-Disposition: form-data;name="ErrorCode"

Success ----20170803161934 Content-Disposition: form-data;name="ErrorMessage"

----20170803161934 Content-Disposition: form-data; name="Payload"

PK ÁIKšŽÌ*• * > 511257719_511257718_837P5010X12BATCH_99000061.199786.1.999.date»Â0E…ùNvB^lQJT1¥CéÀ§äÛkR)`O¾Ç:–s‰ Â¥×Ï´m˜_Ï4æ!æ±G!P+ËGÄŽ• * > 511257719_511257718_837P5010X12BATCH_99000061.199786.1.999.datPK l ñ
----20170803161934


Solution

  • Solution for you is read you byte, parse it to string => compare this string with a pattern which you want to start writing the content (in your case is 'payload'). When you reach this pattern then start to write other part of you stream to file. Here is sample code for you:

    HttpResponse response = services.getFileByPayloadID("12345-abcde");
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    BufferedInputStream bis = null;
    try {
        bis = new BufferedInputStream(response.getEntity().getContent());
    } catch (UnsupportedOperationException | IOException e) {
        e.printStackTrace();
    }
    String filePath = "c:\\sample.zip";
    BufferedOutputStream bos = null;
    try {
        bos = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
        String output = "";
        int inByte;
        String charset = "your-charset"; //using charset to ensure that you can parse string correct to compare it.
        boolean start = false;
        while((inByte = bis.read()) != -1) {
            if (!start){
                buf.write((byte) inByte);
                output = buf.toString(charset);
                if (output.endsWith("name=\"Payload\"")){ //compare with your pattern to determine when will start write to file
                    start = true;
                }
            }
            if(start){
                bos.write(inByte);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {bis.close();} catch (Exception e) {}
        try {bos.close();} catch (Exception e) {}
    }