Getting started - skornei/restserver GitHub Wiki
Let’s get started with RestServer. The first thing you need to do, if you haven’t already done so, is download the RestServer library.
Installing with Gradle
Modify your build.gradle to include:
repositories {
mavenCentral()
maven { url "https://jitpack.io" }
}
compile 'com.github.skornei:restserver:1.0.4+'
Configuring Your Project
In you application class
public class YouApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
RestServerManager.initialize(this);
}
}
Create entity
public class TestEntity {
private String test;
public TestEntity() {
}
public TestEntity(String test) {
this.test = test;
}
public String getTest() {
return test;
}
}
Create converter (example JeckSon)
public class JsonConverter implements BaseConverter {
private ObjectMapper mapper = new ObjectMapper();
@Override
public byte[] writeValueAsBytes(Object value) {
try {
return mapper.writeValueAsBytes(value);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
@Override
public <T> T writeValue(byte[] src, Class<T> valueType) {
try {
return mapper.readValue(src, valueType);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Create authentication class
public class Authentication implements BaseAuthentication {
@Override
public boolean authentication(RequestInfo requestInfo) {
return true;
}
}
Create classes for controllers. Don’t worry though, this part is easy.
@RestController("/ping")
public class PingController {
@GET
@RequiresAuthentication
public void ping() {
System.out.println("work!");
}
@POST
@Produces(ContentType.APPLICATION_JSON)
@Accept(ContentType.APPLICATION_JSON)
public TestEntity test(Context context, RequestInfo request, ResponseInfo response, TestEntity testEntity) {
return new TestEntity(testEntity.getTest() + ":test");
}
private static String getStackTrace(Throwable throwable) {
StringWriter stringWriter = new StringWriter();
throwable.printStackTrace(new PrintWriter(stringWriter));
return stringWriter.toString();
}
@ExceptionHandler
@Produces(ContentType.TEXT_PLAIN)
public void handleThrowable(Throwable throwable, ResponseInfo response) {
String throwableStr = getStackTrace(throwable);
response.setBody(throwableStr.getBytes());
}
}
Create server class
@RestServer( port = MainServer.PORT,
converter = JsonConverter.class, //Optional
authentication = Authentication.class, //Optional
controllers = {PingController.class} )
public class MainServer extends BaseRestServer {
public static final int PORT = 8080;
}
Init module in you class.
private MainServer mainServer = new MainServer();
...
mainServer.start(); or mainServer.stop();
How to check?
curl -i -X POST -H "Content-Type: application/json" -d '{"test":"12345"}' 'http://192.168.1.1:8080/ping'