使用HtmlUnit WebClient为每个请求传递基本身份验证凭据
发布时间:2020-12-14 21:18:23 所属栏目:资源 来源:网络整理
导读:我正在尝试为Web应用程序编写一个简单的冒烟测试. 应用程序通常使用基于表单的身份验证,但也接受基本身份验证,但由于默认情况下是基于表单的身份验证,因此它永远不会发送所需的身份验证,而只是发送登录表单. 在测试中,我尝试使用发送基本的auth头 WebClient
我正在尝试为Web应用程序编写一个简单的冒烟测试.
应用程序通常使用基于表单的身份验证,但也接受基本身份验证,但由于默认情况下是基于表单的身份验证,因此它永远不会发送所需的身份验证,而只是发送登录表单. 在测试中,我尝试使用发送基本的auth头 WebClient webClient = new WebClient(); DefaultCredentialsProvider creds = new DefaultCredentialsProvider(); // Set some example credentials creds.addCredentials("usr","pwd"); // And now add the provider to the webClient instance webClient.setCredentialsProvider(creds); webClient.getPage("<some url>") 我还尝试在WebRequest对象中填充凭据并将其传递给webClient.getPage方法. 但在服务器上我没有获得身份验证标头.我怀疑WebClient只有在服务器明确询问它时才会发送身份验证标头,这种情况从未发生过. 所以问题是如何让WebClient在每个请求上发送Authentication头,包括第一个请求? 解决方法
这可能有所帮助:
WebClient.addRequestHeader(String name,String value) 更具体的一个可以创建这样的身份验证标头 private static void setCredentials(WebClient webClient) { String username = "user"; String password = "password"; String base64encodedUsernameAndPassword = base64Encode(username + ":" + password); webClient.addRequestHeader("Authorization","Basic " + base64encodedUsernameAndPassword); } private static String base64Encode(String stringToEncode) { return DatatypeConverter.printBase64Binary(stringToEncode.getBytes()); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |