How to use RPC protocol (Remote Procedure Call) to send a HTTP request as formatted JSON to a web server?

조회 수: 30 (최근 30일)
I have a instrument that capture a set of data and works as a web service with IP address 172.20.32.192. I want to get some data from this instrument and I'm trying to communicate via Remote Procedure Call protocol (RPC protocol) because this device supports only RPC protocol. In the user manual of it, this expressed that the data exchange format is the JSON (JavaScript Object Notation). To communication, I must send a request via HTTP POST in the body of the HTTP request as a JSON object. The URL to do this is http://IP Address/rpc. According to the user manual contents, an example for request and response must be following:
request = {
"version": "1.0",
"proc": "GetPlantOverview",
"id": "1",
"format": "JSON"
}
response = {
"version": "1.0",
"proc": "GetPlantOverview",
"id": "1",
"result":
{
"overview":
[{
"meta": "GriPwr",
"name": "current power",
"value": "4250",
"unit": "W"
}]}}
I used the webread and webwrite functions with Query name-value pairs or Post name-value pairs like following:
options = weboptions('RequestMethod','post','ArrayFormat','json','Timeout',10);
resp = webread('http://172.20.32.192/rpc','version','1.0','proc','GetPlantOverview','id','1','format','json',options) % or using webwrite
but i got only HTML page that it wasn't like the response. How can i send a HTTP request as formatted JSON via RPC protocol to get data from that instrument? I'll be grateful for helps.

채택된 답변

Robert Snoeberger
Robert Snoeberger 2017년 1월 17일
편집: Robert Snoeberger 2017년 1월 17일
The documentation for webread says that it only supports application/x-www-form-urlencoded for HTTP POST requests [1]. Since you are trying to send application/json, you need to use webwrite. I think the following should do what you want.
>> body.version = '1.0';
>> body.proc = 'GetPlantOverview';
>> body.id = '1';
>> body.format = 'JSON';
>> options = weboptions('MediaType', 'application/json');
>> resp = webwrite('http://172.20.32.192/rpc', body, options)
  댓글 수: 1
rasoul rad
rasoul rad 2017년 1월 20일
Hi Robert, Thank you so much for your answer. With your answer i figured out my problem. According to the user manual, i should have added "RPC=" syntax to my HTTP POST request in JSON format like following:
options = weboptions('RequestMethod','POST','MediaType','application/json','Timeout',10);
req = struct('version','1.0','proc','GetPlantOverview','id','1','format','JSON',);
req1 = jsonencode(req);
req2 = strcat('RPC=',req1); % add "RPC=" syntax to the HTTP request
resp = webwrite('http://172.20.32.192/rpc',req2,options)
Therefore, the response is received correctly. Again, i'm thankful very much for your answer.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 JSON Format에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by