Restlet API(http://restlet.com/)是直接按照 REST 的概念设计的,资源、表示、连接器、组件和媒体类型。
使用该框架可自然地实现 REST API。尽管下面的例子不是纯 RESTful的,但依然展示了只需要很少的一点代码就能创建一个返回 JSON 的服务器。
代码举例:
package com.saternos.embedded;
import org.restlet.*;
import org.restlet.data.*;
import org.restlet.resource.*;
public class TestRestletHttpServer extends ServerResource {
public static void main(String[] args) throws Exception {
Component component = new Component();
component.getServers().add(Protocol.HTTP, Integer.parseInt("8000"));
component.getDefaultHost().attach("/", TestRestletHttpServer.class);
component.start();
}
@Get("json")
public String getGreeting() {
return "{\"testResponse\":\"Hello World\"}";
}
}
POM文件:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.myself</groupId>
<artifactId>temp-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>temp-demo</name>
<url>http://maven.apache.org</url>
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.restlet.jse/org.restlet -->
<dependency>
<groupId>org.restlet.jse</groupId>
<artifactId>org.restlet</artifactId>
<version>2.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.restlet.jse/org.restlet.ext.json -->
<dependency>
<groupId>org.restlet.jse</groupId>
<artifactId>org.restlet.ext.json</artifactId>
<version>2.0.0</version>
</dependency>
</dependencies>
</project>