1
由於我是REST Web服務的新手,我想問一些關於REST API的簡單問題。我已經創建了一個Java應用程序,通過REST提供數據與下面的方法:創建REST/JSON API
@RequestMapping(value = "/JSON/ReceiveData/{metricOne}/{metricTwo}")
public @ResponseBody
String getData(@RequestParam("callback") String callback, @PathVariable String metricType,
@PathVariable String metricPeriod) {
LinkedHashMap<String,String> map = new LinkedHashMap<String, String>();
try{
map = service.getData(metricOne, metricTwo);
}catch(NullPointerException e){
e.printStackTrace();
}
return callback+"("+t2JsonUtil.toJsonString(map)+")";
}
我已經創建了客戶端應用下面的方法來獲得和反序列化爲LinkedHashMap中JSON對象:
public LinkedHashMap getDataClient(String metricOne, String metricTwo) {
LinkedHashMap<String,String> map = null;
try {
URL url = new URL("http://localhost:8081/Metrics/Stats/JSON/ReceiveData/"+metricOne+"/"+metricTwo+"/?callback=");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output = br.readLine();
output = output.substring(1,output.length()-1);
JsonFactory factory = new JsonFactory();
ObjectMapper mapper = new ObjectMapper(factory);
TypeReference<LinkedHashMap<String,String>> typeRef= new TypeReference<LinkedHashMap<String,String>>() {};
map = mapper.readValue(output, typeRef);
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
如果我想創建一個API來爲不同語言的應用程序提供此服務,我應該怎麼做?只需提供包含在getDataClient中的URL?我很困擾。如果有人能夠給我一個解釋(或者一個小例子),我將非常感激。謝謝!