调用REST API Call到外部REST服务器。
一、REST API参数说明
- Endpoint URL pattern
可以是静态字符串,也可以是Message Metadata的属性。
例如,如果消息负载中包含带有属性deviceType值为container,
http://localhost/api/${deviceType}/update
会被解析为:
http://localhost/api/container/update
-
Request method
GET,POST,PUT,DELETE -
Headers
request headers, header or value 可以是静态字符串,也可以是Message Metadata的属性。
可以配置header的名称/值。可以是静态字符串,也可以是Message Metadata的属性。例如$ {deviceType}。 -
Request body
会把完整的消息负载发送给设置的REST服务器。如果需要,可以将规则链配置为使用转换节点后,发送转换节点后的消息负载。 -
Outbound message
出结点消息包含从Rest服务返回的status,statusCode,statusReason和headers做为Message Metadata。消息负载是Rest服务器返回的response body。
如果请求成功,出结点消息将通过Success链传递到下一个节点,否则将使用Failure链。
二、实际实现
- 使用Spring的controller,作为服务端的测试接口。
@RestController
@RequestMapping("/")
public class DataController {
private static final Logger logger = Logger.getLogger(DataController.class);
@RequestMapping(value = "/pushdata")
public Object pushdata(HttpServletRequest request) throws Exception {
String json = getRequestJsonString(request);
logger.info("json=" + json);
return "OK";
}
/***
* 获取 request 中 json 字符串的内容
*
* @param request
* @return : String
* @throws IOException
*/
public static String getRequestPostBytes(HttpServletRequest request) throws IOException {
int contentLength = request.getContentLength();
if (contentLength < 0) {
return null;
}
byte buffer[] = new byte[contentLength];
for (int i = 0; i < contentLength;) {
int readlen = request.getInputStream().read(buffer, i, contentLength - i);
if (readlen == -1) {
break;
}
i += readlen;
}
String charEncoding = request.getCharacterEncoding();
if (charEncoding == null) {
charEncoding = "UTF-8";
}
return new String(buffer, charEncoding);
}
}
-
规则链设置
-
实际效果
实际LOG输出:
2020-10-01 13:14:52.520 INFO c.controller.DataController - json={
"M.TAG.D001" : 2670,
"M.TAG.D002" : 3370,
"M.TAG.D003" : 6400,
"M.TAG.D004" : 8450,
"M.TAG.D005" : 4500,
"M.TAG.D006" : 1355.88,
"M.TAG.D007" : 3082
}