ID to multipart entity

Given we have made a multi part request. We are now needing to ad a content-id. Below is the code that we were trying to use to create the multipart request:

MultipartEntity mpEntity = new MultipartEntity();
StringBody body;
try
{
    body = new StringBody( xml, "application/xml", Charset.forName( "UTF-8" ) );
    byte[] data = getBytesFromFile( image );
    ByteArrayBody bab = new ByteArrayBody( data, "image/jpeg", "test_image_cid" );
    mpEntity.addPart( "body", body );
    mpEntity.addPart( "test_image_cid", bab );

} catch ( UnsupportedEncodingException e )
{
    e.printStackTrace();
}

HttpPost request = new HttpPost("http://10.1.1.1");
request.addHeader( "Authorization", authorization_header_values );
request.addHeader( "Content-Type", "Multipart/Related" );
request.setEntity( mpEntity );
return request;

This is what the webservice that we are calling has requested:

<?xml version="1.0" encoding="utf-8"?> <request method="receipt.create"> 
   <receipt>
       <expense_id>1</expense_id>  <!-- id of expense -->
       <image>cid:xxxxxxxxxxxxx</image> <!-- content-id used on the related binary content -->
   </receipt>
</request>

This is what we are getting back from the server for debugging:

POST / HTTP/1.1 Authorization: OAuth realm="", oauth_version="1.0", oauth_consumer_key="key", oauth_token="token", oauth_timestamp="1358197676614", oauth_nonce="1111111", oauth_signature_method="PLAINTEXT", oauth_signature="signature" Content-Type: Multipart/Related User-Agent: agent Content-Length: 2336363 Host: 10.1.1.1 Connection: Keep-Alive

--HPeiFlrswQmM8Mi1uoWpzJRfrnp3AMtZjpCdt Content-Disposition: form-data; name="body" Content-Type: application/xml; charset=UTF-8 Content-Transfer-Encoding: 8bit

<?xml version='1.0' encoding='UTF-8' ?>
    <request method="receipt.create">
        <receipt>
            <expense_id>979</expense_id>
            <image>cid:test_image_cid</image>
        </receipt>
    </request>

--HPeiFlrswQmM8Mi1uoWpzJRfrnp3AMtZjpCdt Content-Disposition: form-data; name="test_image_cid"; filename="test_image_cid" Content-Type: image/jpeg Content-Transfer-Encoding: binary

We are stuck in figuring out how to add the Content-ID to this request. Is there anything obvious that is missing in this call? IS there another way to build this request? Thanks for any advice!


To add the Content-Id, or any other field for that matter, you have to use a FormBodyPart. Simply put, split up these lines:

ByteArrayBody bab = new ByteArrayBody( data, "image/jpeg", "test_image_cid" );
mpEntity.addPart( "body", body );

Into these lines:

ByteArrayBody bab = new ByteArrayBody( data, "image/png", "byte_array_image" );
FormBodyPart fbp = new FormBodyPart( "form_body_name", bab );
fbp.addField( "Content-Id", "ID_GOES_HERE" );
mpEntity.addPart( fbp );

And that should do it for you!

链接地址: http://www.djcxy.com/p/46480.html

上一篇: php + curl + multipart / form

下一篇: ID到多部分实体