Apache Camel rest获取GET请求的参数

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不适用



  • 7
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值