在PHP中使用REST服务的移动应用程序的Web服务

时间:2012-08-24 10:21:04

标签: php web-services rest restful-architecture

我必须在Rest Service中为移动应用程序(IPhone和Android)创建一个Web服务。此应用程序基于一个电子出版。我尝试了一些基于SLIM的REST服务。我可以将数据添加到数据库中,也可以从数据库中检索数据。

我使用以下链接开发REST服务

http://phpmaster.com/writing-a-restful-web-service-with-slim/

我可以通过html中的表单添加新数据,但我想使用url添加数据。但我不能。这是我使用的代码

<form action="http://localhost/samples/Restfull/samp5/index.php/custom" method="POST">
 <input type="hidden" name="_METHOD" value="POST">
 Name: <input type="text" name="Customer_Name"><br>
 Mobile: <input type="text" name="Customer_Mobile"><br>
 Email: <input type="text" name="Customer_Email"><br>
 Address: <textarea name="Customer_Address"></textarea>
 <br>
 <input type="submit" value="Submit">
</form>

当我尝试通过此表单时,操作已成功完成。但我想把它作为网络服务。我尝试通过url添加数据但失败了,同时使用连接查询删除或获取数据也无法正常工作。

我使用以下函数

从Db检索数据
$app->get("/custom/:id", function ($id) use ($app, $db) {
    $app->response()->header("Content-Type", "application/json");
    $custom = $db->Registration()->where("Registration_Id", $id);
    if ($data = $custom->fetch()) {
        echo json_encode(array(
            "custom_Name" => $data["Customer_Name"],
            "custom_Mobile" => $data["Customer_Mobile"],
            "custom_Email" => $data["Customer_Email"],
            "custom_Address" => $data["Customer_Address"]
            ));
    }
    else{
        echo json_encode(array(
            "status" => false,
            "message" => " $id does not exist"
            ));
    }
});

这也很有效。

是否有其他方式或好的样本可用。不仅在Slim中。我需要集成REST服务。请在此建议。

提前致谢。

1 个答案:

答案 0 :(得分:0)

好的,我认为这是你需要开始的地方:)

如果您要使用url设置数据,则必须使用HTTP get方法。如果您使用java开发restful服务,我建议您使用Jersey(JAX-RS(JSR 311)参考实现来构建RESTful Web服务。)

在项目服务中,您可以使用HTTP get方法

定义方法
@Stateless
@Path("/basepath")
@javax.ws.rs.Produces("application/json")
@javax.ws.rs.Consume("application/json")
public class RestService {

    @Path("/{index}")
    public String M(@PathParam("index") String index){
      //you can use index value here

    }

}

所以,在您的网址中的“basepath /”之后,您可以使用该值。

如果您想开始使用restful服务,Netbeans很容易实现。 这里有一些可能对你有帮助的链接。

netbeans.org/kb/docs/websvc/rest.html
netbeans.org/kb/docs/websvc/intro-ws.html