restlet2.1 学习笔记(九)简单验证客户端用户名与密码

来源:互联网 发布:网店美工 编辑:程序博客网 时间:2024/06/05 14:20

权限是系统中必不可少的。

客户端访问服务器的过程为:  客户端发起请求  -> 服务器路由 -> 访问服务端资源

如果要使用安全验证,可以在路由之前验证:  客户端发起请求  -> 认证 -> 服务器路由 -> 访问服务端资源


第一步:编写服务端资源

public interface MovieResource {@Getpublic String getMovieInfo();@Putpublic String uploadMovie(Movie movie) throws IOException ;}

第二步:实现资源

public class MovieServerResource extends ServerResource implements MovieResource{public String uploadMovie(Movie movie) throws IOException{String result = String.format("upload movie{name:%s size:%d minutes:%d} success!" ,movie.getName() ,    movie.getSize(),movie.getMinutes());  return result ;  }@Overridepublic String getMovieInfo() {return "movie info";}}

第三步:创建应用配置路由与认证管理器

public class MovieApplication extends Application{/** * 注意:Router 与 ChallengeAuthenticator 均是Restlet的子类 */@Overridepublic Restlet createInboundRoot() {Router router = new Router(getContext());//绑定资源router.attach("/" , MovieServerResource.class);//创建认真器ChallengeAuthenticator authenticator = new ChallengeAuthenticator(getContext(), ChallengeScheme.HTTP_BASIC, "Movie Realm");//配置用户MapVerifier verifier = new MapVerifier();verifier.getLocalSecrets().put("zhoufeng", "123456".toCharArray());authenticator.setVerifier(verifier);//将路由器放在认证器之后authenticator.setNext(router);//返回认证器return authenticator ;}}


第四步:启动服务器

public class MovieServer {public static void main(String[] args) throws Exception {Component comp = new Component() ;comp.getServers().add(Protocol.HTTP , 8888) ;comp.getDefaultHost().attach(new MovieApplication());comp.start(); }}
此时用浏览器访问http://localhost:8888 会提示输入用户名和密码


客户端代码示例:

public class MovieClient {/** * 不使用用户名密码直接访问Get方法,将会抛出异常 */@Testpublic void test01() throws IOException{ClientResource cr = new ClientResource("http://localhost:8888/");cr.get().write(System.out);}    /** * 加入用户名密码访问Get方法,成功得到返回值 */@Testpublic void test02() throws IOException{ClientResource cr = new ClientResource("http://localhost:8888/");cr.setChallengeResponse(ChallengeScheme.HTTP_BASIC , "zhoufeng", "123456");cr.get().write(System.out);  }  /** * 不使用用户名密码访问put方法 */@Testpublic void test03() throws IOException{MovieResource mr = ClientResource.create("http://localhost:8888/", MovieResource.class);Movie movie = new Movie();movie.setName("速度与激情6");movie.setSize(10000000l);movie.setMinutes(120);String result = mr.uploadMovie(movie);System.out.println(result );  }/** * 使用用户名密码访问put方法 */@Testpublic void test04() throws IOException{ClientResource cr = new ClientResource("http://localhost:8080/");cr.setChallengeResponse(ChallengeScheme.HTTP_BASIC , "zhoufeng", "123456");MovieResource mr = cr.wrap(MovieResource.class);Movie movie = new Movie();movie.setName("速度与激情6");   movie.setSize(10000000l);movie.setMinutes(120);String result = mr.uploadMovie(movie);System.out.println(result);}}



原创粉丝点击