Since rest integration is commonly used with Post request.
When we do post request with only Text Param then it's simple to pass Text Param in Body in requested format.
In some scenarios we may need to pass Blob(Img/Doc) with Text param or without Text param.
Following are the key point for Blob(Img/Doc) in HTTP Post request with Text param or without text.
1. Encoding : The Blob body should be encoded with following approach.
EncodingUtil.base64Encode(doc.Body)
2. Content Type in Header : Content type format should be in following format
req.setHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
3. Boundary : The boundary parameter is set to a number of hyphens plus a random string at the end, but you can set it to anything at all. The problem is, if the boundary string shows up in the request data, it will be treated as a boundary.
4. Body : Body as a string is very important in this scenario. So body should be created carefully.
private static final String CRLF = '\r\n';
private static final String CHAR = 'UTF-8';
final String boundary = '---------------JKKJLJLJLJLJL';
body+=('--')+boundary+(CRLF);
body+=('Content-Disposition: form-data; name="name"')+(CRLF);
body+=('Content-Type: application/json; charset=' + CHAR)+(CRLF);
body+=(CRLF);
body+='{"Text Param":{"Text Param Value"}}'+(CRLF);
/* if Text param is not needed this above line can be skipped*/
body+=('--')+boundary+(CRLF);
body+=('Content-Disposition: form-data; name="file"; filename="' + filename + '"')
+(CRLF);
body+=('Content-Type: text/plain')+(CRLF);
body+=(CRLF);
body+=EncodingUtil.base64Encode(doc.Body);
body+=(CRLF);
body+=('--')+boundary+('--')+(CRLF);
5. Complete Code
//specify the enedpoint variable
String targetURL = 'End Point';
Document doc = [SELECT ContentType,id, Name, body FROM Document WHERE Id = '***************'];
String fileName = doc.Name;
String loginToken ='LoginToken'
string body = '';
final String boundary = '---------------JKKJLJLJLJLJL';
body+=('--')+boundary+(CRLF);
body+=('Content-Disposition: form-data; name="name"')+(CRLF);
body+=('Content-Type: application/json; charset=' + CHARSET)+(CRLF);
body+=(CRLF);
body+='{"Text Param":{"Text Param Value"}}'+(CRLF);
body+=('--')+boundary+(CRLF);
body+=('Content-Disposition: form-data; name="file"; filename="' + filename + '"')
+(CRLF);
body+=('Content-Type: text/plain')+(CRLF);
body+=(CRLF);
body+=EncodingUtil.base64Encode(doc.Body);
body+=(CRLF);
body+=('--')+boundary+('--')+(CRLF);
System.debug('----->'+body);
HttpRequest req = new HttpRequest();
req.setEndpoint(targetURL);
req.setHeader('x-auth-token', loginToken);
req.setHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
req.setMethod('POST');
req.setBody(body);
Http http = new Http();
HTTPResponse res = http.send(req);
System.debug('**** response '+res.getBody());
System.debug('**** response '+res.getStatus());
No comments:
Post a Comment