如何为已有站点创建Restful服务

时间:2013-12-09 08:09:27

标签: java web-services rest tomcat7

我有一些API网站会生成一些JSON数据,但我无法直接使用该URL访问该数据(如果我尝试访问它,请说oauth错误)所以为此我有一个密钥和lib文件抛出那个例外。

所以我想为此创建一个Restful Web服务,......

没有restful服务,我从一个在main()方法中调用的类文件访问数据,如果我作为java应用程序运行它我在控制台获取数据,...因此它有主要方法,.. 但我需要构建一个Restful Web服务。并在移动窗口/ iPhone / android

中检索数据

我知道什么是Restful服务但我不知道如何获取数据java文件数据,...在控制台,...到Restful服务

2 个答案:

答案 0 :(得分:1)

根据您对问题的看法,您可以编写一个包装器REST类来调用当前方法并将响应发送回用户。详细说明它,说你当前的类是A,它的方法是getData(),它目前从main方法调用。现在,您使用方法say data()创建一个REST类,并且在此函数中,您只是返回A.getData()。 您可以根据需要添加其他配置,如注释,参数类型等。

答案 1 :(得分:1)

试试这个

您的网络服务方法中包含以下内容的代码

public String myMethos(){

        String urlString="http://example.com/WS/StaticExample.php?method=sayHello&name=World";
        URL url=new URL(urlString);
        URLConnection connection=url.openConnection();
        connection.setDoOutput(true);
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.close();
        JSONObject jsonobj = null;
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String decodedString="",URLstrJson="";

        while ((decodedString = in.readLine()) != null) {
          URLstrJson+=decodedString;
        }

假设您的URLtrJson值如下所示

{
"worldpopulation":
[
{
"rank":1,
"country":"China",
"population":"1,354,040,000",
"flag":"http://www.androidbegin.com/tutorial/flag/china.png"
}
]
}

然后,

    jsonobj=new JSONObject(URLstrJson);

    System.out.println(jsonobj.toString());
    return jsonobj.toString();

}