Apache Camel rest组件内部可以使用多个框架实现rest,比如restlet、jetty、servlet等等,我这里使用restlet
首先加入依赖
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-restlet</artifactId>
<version>2.15.2</version>
<scope>provided</scope>
</dependency>
这里先配置一个简单的rest服务
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:camel="http://camel.apache.org/schema/spring"
xsi:schemaLocation="
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="product" class="com.pp.ProductProcessor" />
<camelContext id="restCamelContext" xmlns="http://camel.apache.org/schema/spring">
<restConfiguration bindingMode="auto" contextPath="" component="restlet" port="3387"/>
<rest path="/api">
<!-- 访问路径 http://127.0.0.1:3387/api/products -->
<get uri="/products" >
<to uri="direct:products" />
</get>
</rest>
<route>
<from uri="direct:products" />
<to uri="bean:product?method=parameter" />
</route>
</camelContext>
</beans>
启动服务之后,当我们访问
http://127.0.0.1:3387/api/products?id=101&type=0 之后,就会进入到ProductProcessor类的parameter方法
那么在parameter方法里面,如何获取到这个url的参数呢?
有如下两个方法
一:
String queryString = exchange.getIn().getHeader(Exchange.HTTP_QUERY, String.class);
这样就获取到了url问号后面的所有字符串,然后,分割获取指定的参数
这里使用JDK1.8一行代码搞定
String queryString = "id=1&type=cmcc&name=admin";
Map<String, String> map = Stream.of(queryString.split("&")).map(obj -> obj.split("=")).collect(Collectors.toMap(entry -> entry[0], entry -> entry[1]));
二:
package com.pp;
import java.util.Map;
import org.apache.camel.Exchange;
import org.apache.camel.component.restlet.RestletConstants;
import org.restlet.data.Form;
import org.restlet.engine.adapter.HttpRequest;
public class ProductProcessor
{
public void parameter(Exchange exchange)
{
HttpRequest req = exchange.getIn().getHeader(RestletConstants.RESTLET_REQUEST, HttpRequest.class);
Form form = req.getResourceRef().getQueryAsForm();
//这个map就是url上面的所有参数
Map<String, String> maps = form.getValuesMap();
System.out.println(maps.get("id"));//获取id参数
System.out.println(maps.get("type"));//获取type参数
exchange.getOut().setBody("this is out body");
}
}
注意:这里的方法二只适用于restlet实现的rest,其它框架实现的rest不适用