首先給出curl的說明:測試命令,-i 表示交互式,打印HTTP的頭信息,-H 追加指定自己的頭格式,-d 數據部分.
比如:
curl -i -H 'Content-Type:application/json' -d '{"jsonrpc":"2.0", "method":"greet", "params":{"name":"I am mark"}, "id":"200"}' http://127.0.0.1:4000
python的服務器,最好單獨搭建一個虛擬服務器,需要pip安裝
Werkzeug, json-rpc, jsonrpclib,python要求2.7 版本
下面的兩份代碼可以在這里找到.
# -*- coding: utf-8 -*-
from werkzeug.wrappers
import Request, Response
from werkzeug.serving
import run_simple
from jsonrpc
import JSONRPCResponseManager, dispatcher
@dispatcher.add_method
def foobar(**kwargs):
return kwargs[
"foo"] + kwargs[
"bar"]
@dispatcher.add_method
def greet( name ):
return "hello "+ name
@Request.application
def application(request):
# Dispatcher is dictionary {<method_name>: callable}
dispatcher[
"echo"] =
lambda s: s
dispatcher[
"add"] =
lambda a, b: a + b
#dispatcher["greet"] = lambda n: "hello "+ n
response = JSONRPCResponseManager.handle(
request.data, dispatcher)
return Response(response.json, mimetype=
'application/json')
if __name__ ==
'__main__':
run_simple(
'localhost', 4000, application)
客戶端代碼:
# -*- coding: utf-8 -*-
import jsonrpclib
server = jsonrpclib.Server(
'http://127.0.0.1:4000')
print server.add(1,2)
print server.echo(
"hello world")
print server.foobar( foo=
"hello", bar=
" world!")
print server.greet(
"roc")
這是curl的命令行測試: curl -i -H 'Content-Type:application/json' -d '{"jsonrpc":"2.0", "method":"foobar", "params":{"foo":"hello ", "bar":"world"}, "id":"200"}' http://127.0.0.1:4000
看
通過Zabbix API獲取歷史監控數據 有稍微詳細的介紹:
這個鏈接介紹了幾乎所有語言的jsonRPC的實現:
JSON-RPC implementation這里用到這里列表里面的object-c實例:(當然要去先下載工程那個文件)
//
// AppDelegate.m
// objc-JSONRpc
//
// Created by Rasmus Styrk on 8/28/12.
// Copyright (c) 2012 Rasmus Styrk. All rights reserved.
//
#import "AppDelegate.h"
#import "JSONRPCClient+Invoke.h" // To allow use of invokes
#import "JSONRPCClient+Notification.h" // To allow use of notifications
#import "JSONRPCClient+Multicall.h" // Add multicall support
@implementation AppDelegate
- (void)dealloc
{
[_window release];
[super dealloc];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Standard stuff
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
NSString *url = @"http://127.0.0.1:4000";
NSDictionary *params = @{@"foo":@"hello ", @"bar":@"world"};
NSString *method = @"foobar";
// RPC Test
JSONRPCClient *rpc = [[JSONRPCClient alloc] initWithServiceEndpoint:url];
[rpc invoke:method params:params onSuccess:^(RPCResponse *response) {
NSLog(method);
NSLog(@"Respone: %@", response);
NSLog(@"Result: %@", response.result);
} onFailure:^(RPCError *error) {
NSLog(method);
NSLog(@"Error: %@", error);
}];
[rpc release];
self.window.rootViewController = [[[UIViewController alloc] init] autorelease];
return YES;
}
@end