将Content-ID添加到多部分实体

时间:2013-01-14 21:34:56

标签: java android httprequest

鉴于我们已提出多部分请求。我们现在需要提供内容ID。下面是我们尝试用来创建多部分请求的代码:

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;

这就是我们要求的网络服务所要求的:

<?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>

这是我们从服务器返回进行调试的内容:

POST / HTTP / 1.1 授权: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 =“签名” 内容类型:多部分/相关 用户代理:代理 内容长度:2336363 主持人:10.1.1.1 连接:Keep-Alive

- HPeiFlrswQmM8Mi1uoWpzJRfrnp3AMtZjpCdt 内容处理:表格数据; NAME = “体” Content-Type:application / xml;字符集= UTF-8 内容传输编码:8位

<?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 内容处理:表格数据; NAME = “test_image_cid”;文件名= “test_image_cid” 内容类型:image / jpeg 内容传输编码:二进制

我们一直在搞清楚如何将Content-ID添加到此请求中。这次电话会有什么明显的遗漏吗?有另一种方法来构建此请求吗?谢谢你的建议!

1 个答案:

答案 0 :(得分:4)

要添加Content-Id或任何其他字段,您必须使用FormBodyPart。简单地说,分开这些行:

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

进入以下几行:

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 );

这应该适合你!