1

As I am a novice to REST web services, I would like to ask something simple about REST APIs. I have created a Java application that provides data via REST with the following method:

@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)+")";
}

I have created the following method for the client application to obtain and deserialize into a LinkedHashMap the JSON object:

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;

}

If I want to create an API in order to offer this service to applications of different languages, what should I do exactly? Just provide the URL included in the getDataClient? I am very confused. I would be very grateful if someone could give me a explanation (or a small example) about this. Thanks!

4

1 回答 1

3

如果我想创建一个 API 以便为不同语言的应用程序提供此服务,我应该怎么做?

Web 服务的主要目的之一是允许异构(不同技术)系统之间的通信。REST 服务基于 HTTP 协议构建,因此任何支持 HTTP 通信的客户端技术都可以使用您的 REST 服务。

只需提供包含在 getDataClient 中的 URL?

URL 用于识别每个实体,但您可能还必须提供其他信息,例如:输入参数详细信息、所需标头等。最好编写一个小规范或您的 REST API 使用指南,以帮助客户轻松无缝地使用您的服务。

于 2013-10-03T09:09:53.107 回答