使用基本身份验证,您根本不需要进入任何登录页面。如果服务器配置为使用基本身份验证,那么如果在请求中包含基本身份验证标头,则可以向任何受保护的页面发出请求。Jersey过滤器可以解决这一问题。因此,如果基本身份验证确实是服务器正在使用的身份,那么您的代码应该可以工作。
鉴于它不起作用以及它不起作用的方式,我很确定服务器已配置为使用基于表单的身份验证,而不是基本身份验证。
为了使基于表单的身份验证有效,您必须发送包含表单数据(包括用户名和密码)的发布请求才能登录,然后将您从服务器收到的cookie设置为后续请求(因为服务器-
一旦登录, in-将设置会话cookie)。
看一下login.html的样子-它应该包含一个表单。如果使用的是标准servlet表单身份验证,则该表单的操作URL应该为“
j_security_check”,并且应该有两个表单参数:j_username和j_password。如果是这样,您可以尝试以下操作:
String URL_LOGIN = "http://localhost:9080/foo/j_security_check";String URL_DATA = "http://localhost:9080/foo/auth.html";Client client = Client.create();// add a filter to set cookies received from the server and to check if login has been triggeredclient.addFilter(new ClientFilter() { private ArrayList<Object> cookies; @Override public ClientResponse handle(ClientRequest request) throws ClientHandlerException { if (cookies != null) { request.getHeaders().put("cookie", cookies); } ClientResponse response = getNext().handle(request); // copy cookies if (response.getcookies() != null) { if (cookies == null) { cookies = new ArrayList<Object>(); } // A simple addAll just for illustration (should probably check for duplicates and expired cookies) cookies.addAll(response.getcookies()); } return response; }});String username = "me";String password = "me";// Login:WebResource webResource = client.resource(URL_LOGIN);com.sun.jersey.api.representation.Form form = new Form();form.putSingle("j_username", username);form.putSingle("j_password", password);webResource.type("application/x-www-form-urlenpred").post(form);// Get the protected web page:webResource = client.resource(URL_DATA);String response = webResource.get(String.class);我尚未对此进行测试,因此可能会有一些错别字或错误。



