jsonrpc4j+Spring例子

依赖jar包:

<dependency>
    <groupId>com.github.briandilley.jsonrpc4jgroupId>
    <artifactId>jsonrpc4jartifactId>
    <version>1.5.0version>
dependency>

接口文件:

public interface TestManager {
    String hello();
    String helloName(String name, String content)
}

实现类:

public class TestManagerImpl implements TestManager {
    public String hello() {
        return "hello";
    }
    public String helloName(String name, String content) {
        return "name:" + name + ",content:" + content;
    }
}

applicationContext.xml文件:


 
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>

<bean class="com.googlecode.jsonrpc4j.spring.AutoJsonRpcServiceImplExporter" />
<bean class="com.project.manager.impl.TestManagerImpl" />

<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<bean id="testManager" class="com.project.manager.impl.TestManagerImpl" />
<bean name="/test.json" class="com.googlecode.jsonrpc4j.spring.JsonServiceExporter">
    <property name="service" ref="testManager"/>
    <property name="serviceInterface" value="com.project.manager.TestManager"/>
bean> 

单元测试类:

@Test
public void testGetHello() {
    String url = "http://localhost/test.json?method=hello&id=1";
    String result = HttpUtil.get(url);
    System.out.println(result);
}

返回结果:

{"jsonrpc":"2.0","id":1,"result":"hello"}
@Test
public void testGetHelloName() {
    String param = Base64.encode("[\"张三\",\"李四\"]");
    String url = "http://localhost/test.json?method=helloName&id=1¶ms=" + param;        
    String result = HttpUtil.get(url);
    System.out.println(result);
}

返回结果:

{"jsonrpc":"2.0","id":1,"result":"name:张三,content:李四"}
@Test
public void testPost() {
    try {           
         JsonRpcHttpClient client = new JsonRpcHttpClient(new URL("http://localhost/test.json"));
         String result = client.invoke("helloName", new Object[]{"王五", "赵六"}, String.class);
         System.out.println(result);
    } catch (Exception e) {
        e.printStackTrace();
    } catch (Throwable e) {
        e.printStackTrace();
    }
}

返回结果:

name:王五,content:赵六

完整项目代码:http://download.csdn.net/detail/sx5273/9857300

详细内容请参照:https://github.com/briandilley/jsonrpc4j

你可能感兴趣的:(编程语言)