Camel作为REST服务的HTTP代理 - 如何路由路径和参数?

时间:2015-05-12 16:22:00

标签: rest servlets proxy apache-camel

我正在尝试使用Apache Camel作为REST服务的HTTP代理,在中间执行一些auth,并且有一个看起来像这样的路由(为了测试目的而删除了auth):

from("servlet:apiwrapper?matchOnUriPrefix=true")
.to("http://HOST/BASEPATH?bridgeEndpoint=true&throwExceptionOnFailure=false");

访问Camel Servlet路径时如下:

http://CAMELHOST/apiwrapper/node
http://CAMELHOST/apiwrapper/node/stuff/blah?etc=t

依此类推......我希望将这些内容传达给:

http://HOST/BASEPATH/node
http://HOST/BASEPATH/node/stuff/blah?etc=t

但是我当前的路由配置只是将请求发送到

http://HOST/BASEPATH

如果没有追加任何路径/ url参数,我需要附加。如果我关闭bridgeEndpoint,那么当路由到达.to(HTTP)部分时,我只会抛出错误。

如何配置此路线以映射那些?

1 个答案:

答案 0 :(得分:3)

最后,我无法找到一个简单的方法来在配置中执行此操作,因此我在http端点的路由输入和末尾之间添加了一个bean,它执行了一些转换并添加了基本身份验证,看起来像这样:

<template name="User">
  <ul>
    {{#each objectToPairs Address}}
      <li>{{key}} - {{value}}</li>
    {{/each}}
  </ul>
</template>

我的路线看起来像这样,带有虚拟主机和参数:

  // Get all of the request path, including url params, after the context path of this camel app
  HttpServletRequest request = exchange.getIn().getHeader(Exchange.HTTP_SERVLET_REQUEST, HttpServletRequest.class);
  // Use the code below to get the request path instead of .getPathInfo(), as getPathInfo ignores url params
  String path = request.getRequestURI().substring(request.getContextPath().length());

  // Override the dummy host with the wrapped host
  exchange.getIn().setHeader(Exchange.HTTP_URI, "http://baseurl");
  // Override the path that was in the exchange before
  exchange.getIn().setHeader(Exchange.HTTP_PATH, path);
  // Finally override the request params
  exchange.getIn().setHeader(Exchange.HTTP_QUERY, request.getQueryString());

  // Set basic auth headers
  String basicAuth = String.format("%s:%s", "USERNAME", "PASSWORD");
  StringBuilder authHeader = new StringBuilder("Basic ");
  authHeader.append(Base64.encodeBase64String(basicAuth.getBytes(Charsets.UTF_8)));
  exchange.getIn().setHeader("Authorization", authHeader.toString());