78.7. camel-cxfrs プロデューサーを介して REST サービスを呼び出す方法
CXF JAXRS フロントエンドは、プロキシーベースのクライアント API を実装します。この API を使用すると、プロキシーを介してリモート REST サービスを呼び出すことができます。camel-cxfrs プロデューサーは、この プロキシー API に基づいています。
メッセージヘッダーで操作名を指定し、メッセージボディーでパラメーターを準備するだけで、camel-cxfrs プロデューサーが適切な REST リクエストを生成します。
以下に例を示します。
Exchange exchange = template.send("direct://proxy", new Processor() {
public void process(Exchange exchange) throws Exception {
exchange.setPattern(ExchangePattern.InOut);
Message inMessage = exchange.getIn();
// set the operation name
inMessage.setHeader(CxfConstants.OPERATION_NAME, "getCustomer");
// using the proxy client API
inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_USING_HTTP_API, Boolean.FALSE);
// set a customer header
inMessage.setHeader("key", "value");
// setup the accept content type
inMessage.setHeader(Exchange.ACCEPT_CONTENT_TYPE, "application/json");
// set the parameters , if you just have one parameter
// camel will put this object into an Object[] itself
inMessage.setBody("123");
}
});
// get the response message
Customer response = (Customer) exchange.getOut().getBody();
assertNotNull("The response should not be null ", response);
assertEquals("Get a wrong customer id ", 123, response.getId());
assertEquals("Get a wrong customer name", "John", response.getName());
assertEquals("Get a wrong response code", 200, exchange.getOut().getHeader(Exchange.HTTP_RESPONSE_CODE));
assertEquals("Get a wrong header value", "value", exchange.getOut().getHeader("key"));
CXF JAXRS フロントエンドは、 http 中心のクライアント API も提供します。 この API を camel-cxfrs プロデューサーから呼び出すこともできます。HTTP_PATH と HTTP_METHOD を指定し、URI オプション httpClientAPI を使用するか、メッセージヘッダー CxfConstants.CAMEL_CXF_RS_USING_HTTP_API を設定して、プロデューサーが http セントリッククライアント API を使用できるようにする必要があります。レスポンスオブジェクトを、メッセージヘッダー CxfConstants.CAMEL_CXF_RS_RESPONSE_CLASS で指定された型クラスに変換できます。
Camel 2.1 から、CXFRS http セントリッククライアントの cxfrs URI からクエリーパラメーターを指定することもサポートしています。
エラーフォーマットマクロ: スニペット: java.lang.IndexOutOfBoundsException: インデックス: 20、サイズ: 20
動的ルーティングをサポートするには、CxfConstants.CAMEL_CXF_RS_QUERY_MAP ヘッダーを使用して URI のクエリーパラメーターをオーバーライドし、そのパラメーターマップを設定します。