tyoshikawa1106のブログ

- Force.com Developer Blog -

SFDC:Apexで『Content-Type: multipart/form-data』のAPIを実行

ApexではHttpRequestをつかって外部APIを実行することができます。『Content-Type: multipart/form-data』の実行がうまくいかずに困っていたのですが、実行方法を教えてもらったのでメモ。


下記のcurlコマンドで実行できる処理があります。

$ curl -X POST -H "Cache-Control: no-cache" -H "Content-Type: multipart/form-data;" -F "grant_type=password" -F “client_id=[sample]" -F "client_secret=[sample]" -F "username=[sample]" -F "password=[sample]" "http://[sample]”


これをApexから実行するとこうなります。

// Body
String boundary = '------------' + String.valueOf(DateTime.now().getTime());
String body  = '';
body += this.create_multi_param(boundary, 'grant_type', 'password');
body += this.create_multi_param(boundary, 'name', '[sample]');
body += this.create_multi_param(boundary, 'client_id', '[sample]');
body += this.create_multi_param(boundary, 'client_secret', '[sample]');
body += this.create_multi_param(boundary, 'username', '[sample]');
body += this.create_multi_param(boundary, 'password', '[sample]');
body += '--' + boundary + '--\r\n';

Http http = new Http();
HttpRequest req = new HttpRequest();
req.setHeader('Cache-Control', 'no-cache');
req.setHeader('Content-Length', String.valueOf(body.length()));
req.setHeader('Content-Type', 'multipart/form-data; boundary='+ boundary);
req.setEndpoint('http://[sample]');
req.setBody(body);
req.setMethod('POST');
HttpResponse res = http.send(req);
System.debug(res.getBody());

「create_multi_param」メソッドの処理はこんな感じ。

private String create_multi_param(String boundary, String name, String val){
    String param = '--' + boundary+'\r\n'
    + 'Content-Disposition: form-data; name="' + name + '"'
    + '\r\n\r\n' + val + '\r\n';
    return param;
}


これで『Content-Type: multipart/form-data』のAPIを実行できました。boundary変数に「----」やシステム日時をセットしていますがこれはユニークな文字列を生成するためのものです。これを区切り文字として使用すればいいとのことです。

その他のContent-TypeのAPI

GET処理の場合

Http http = new Http();
HttpRequest req = new HttpRequest();
req.setHeader('Cache-Control', 'no-cache');
req.setHeader('Authorization', 'OAuth ' + <token>);
req.setHeader('Content-Type', 'application/json; charset=utf-8');
req.setEndpoint('http://<sample>');
req.setMethod('GET');
HttpResponse res = http.send(req);


POST処理の場合

// API実行
Http http = new Http();
HttpRequest req = new HttpRequest();
req.setHeader('Cache-Control', 'no-cache');
req.setHeader('Authorization', 'OAuth ' + <token>);
req.setHeader('Content-Type', 'application/x-www-form-urlencoded');
req.setEndpoint('http://<sample>');
req.setMethod('POST');
req.setBody(body);
HttpResponse res = http.send(req);


こんな感じです。

Apexコールアウトのサンプル

参考

こちらのリンクも教えてもらったのでメモ