wgetやcurlを使ってJSONメッセージをHTTPリクエストに載せる方法。
POSTメッセージを使えばリクエストボディに情報を含めることができる。これを用いて、JSONメッセージをHTTPリクエストメッセージに載せる。
1. curl版
curl -v -H "Accept: application/json" -H "Content-type: application/json"
-X POST -d {JSONデータ} {URI}
認証はまた別の機会に記載する予定。
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sample;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObjectBuilder;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.PathParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
/**
* REST Web Service
*
* @author USER
*/
@Path("Sample")
public class SampleResource {
@Context
private UriInfo context;
/**
* Creates a new instance of SampleResource
*/
public SampleResource() {
}
/**
* Retrieves representation of an instance of sample.SampleResource
* @return an instance of java.lang.String
*/
@GET
@Produces("application/json")
public String getJson() {
String json;
JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
JsonObjectBuilder objBuilder = Json.createObjectBuilder();
objBuilder.add("time", "2015/01/23 14:30:25");
objBuilder.add("value", 45.5);
arrayBuilder.add(objBuilder);
objBuilder.add("time", "2015/01/23 14:30:25");
objBuilder.add("value", 45.5);
arrayBuilder.add(objBuilder);
JsonArray jsonArray = arrayBuilder.build();
json = jsonArray.toString();
return json;
}
/**
* PUT method for updating or creating an instance of SampleResource
* @param content representation for the resource
* @return an HTTP response with content of the updated or created resource.
*/
@PUT
@Consumes("application/json")
public void putJson(String content) {
}
}
出力はこんな感じになります。[
{
"time":"2015/01/23 14:30:25",
"value":45.5
},{
"time":"2015/01/23 14:30:25",
"value":45.5
}
]