使用HtmlUnit WebClient传递每个请求的基本身份验证凭据 [英] Passing basic auth credentials with every request with HtmlUnit WebClient

查看:1102
本文介绍了使用HtmlUnit WebClient传递每个请求的基本身份验证凭据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为Web应用程序编写简单的冒烟测试。

I'm trying to write a simple smoke test for a web application.

应用程序通常使用基于表单的身份验证,但也接受基本身份验证,但是默认是基于表单的身份验证,它永远不会发送所需的身份验证,而只是发送登录表单。

The application normally uses form based authentication, but accepts basic auth as well, but since the default is form based authentication, it never sends an authentication required, but instead just sends the login form.

在测试中我尝试使用<发送基本身份验证头/ p>

In the test I try to send the basic auth header using

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>")

I还尝试在WebRequest对象中填充凭据并将其传递给 webClient.getPage 方法。

I also tried stuffing the credentials in a WebRequest object and passing that to the webClient.getPage method.

但是在服务器我没有获得身份验证标头。我怀疑WebClient只有在服务器明确要求的情况下才会发送身份验证标头,这种情况从未发生过。

But on the server I don't get an authentication header. I suspect the WebClient only sends the authentication header if it get explicitly asked for it by the server, which never happens.

所以问题是如何让WebClient发送每个请求的身份验证标头,包括第一个?

So the question is how can I make the WebClient send the Authentication header on every request, including the first one?

推荐答案

这可能会有所帮助:

WebClient.addRequestHeader(字符串名称,字符串值)

更具体的一个可以创建这样的认证标题

More specific one can create an authentication header like this

 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());
  }

这篇关于使用HtmlUnit WebClient传递每个请求的基本身份验证凭据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆