REST服务返回

时间:2015-04-19 07:29:37

标签: java rest service

我已经制作了一个REST客户端服务器,一切都或多或少都有效。这就是困境:我可以选择通过用户名检索用户,当用户实际存在时,该用户工作正常。但是,当他没有时,我得到204个http代码,这很好,因为我做了一个null返回。我希望我的方法在找不到用户时将一个普通字符串返回给客户端控制台,比如“没有找到这样的用户......”,但是方法返回类型是逻辑上的User(类),以返回用户对象时找到了。 这是服务器端:

@GET
    @Path("/{uName}")
    @Produces({ "application/json", "application/xml"})
    public User getUserByUsername(@PathParam("uName") String uName) {

        returnAll = usrList.getUsers();

        for (User u : returnAll) {
            if (u.getUserName().equals(uName))
                return u;
        }

        return null;
    }

以下是客户的相关部分:

        case 3:
            sc.nextLine();
            System.out.println("Enter username");
            userName = sc.nextLine();

            restConnect("http://localhost:8080/rest/user/"
                    + userName, "GET");

            promptKey();

更改方法以返回String类型显然会在实际找到用户时中断代码。我该怎么做两种类型的返回功能?感谢

编辑: 找到用户后,我的方法将返回列表中第一个用get(0)的用户,这是错误的。这是我用ID的

测试一些东西的残余物

EDITx2:工作客户

        case 3:
            sc.nextLine();
            System.out.println("Enter username");
            userName = sc.nextLine();

            try{
            restConnect("http://localhost:8080/rest/user/"
                    + URLEncoder.encode(userName, "UTF-8"), "GET");
            }
            catch(RuntimeException e){
                System.out.println("No such user...");
            }
            promptKey();

1 个答案:

答案 0 :(得分:1)

当用户不存在时,您的代码应该返回4xx错误,并且当返回错误时客户端应该有分支。

考虑一下你自己没有开发的客户端应该如何工作,API的定义可能会更清楚。

有关其他结果代码的详细信息,请参阅http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html