由于到目前为止的反馈,已重写...
我有一个Java方法尝试在selenium脚本中通过httpget下载文件,它看起来像是......
private String downloader(WebElement element, String attribute, String filePath) throws IOException, NullPointerException, URISyntaxException {
String fileToDownloadLocation = element.getAttribute(attribute);
fileToDownloadLocation = fileToDownloadLocation.replace("\\", "%5C");
URL fileToDownload = new URL(fileToDownloadLocation);
URI FileDL = new URI(fileToDownload.toString());
File downloadedFile = new File(this.localDownloadPath + filePath);
if (downloadedFile.canWrite() == false) downloadedFile.setWritable(true);
CloseableHttpClient httpclient = HttpClients.createDefault();
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY,new NTCredentials("useraccount", "testpassword", "machinename", "mydomain"));
HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
HttpGet httpget = new HttpGet(FileDL);
CloseableHttpResponse response = httpclient.execute(httpget, context);
this.httpStatusOfLastDownloadAttempt = response.getStatusLine().getStatusCode();
FileUtils.copyInputStreamToFile(response.getEntity().getContent(), downloadedFile);
response.getEntity().getContent().close();
String downloadedFileAbsolutePath = downloadedFile.getAbsolutePath();
return downloadedFileAbsolutePath;
}
当我在常规链接上使用它时(例如从bbc下载文件),一切正常。问题是我使用它的系统是一个使用Windows身份验证来确定是否允许访问的内部系统。当我尝试在这个内部系统上使用它时,我的Http响应结束了: -
HTTP/1.1 401 Unauthorized [Cache-Control: no-cache, no-store, must-revalidate, Pragma: no-cache, Content-Type: text/html, Expires: -1, Server: Microsoft-IIS/7.5, WWW-Authenticate: Negotiate, WWW-Authenticate: NTLM, X-Powered-By: ASP.NET, X-UA-Compatible: IE=edge, Date: Mon, 17 Mar 2014 14:52:43 GMT, Content-Length: 1293]
如果我调试它并获取它使用的URL我可以手动将其粘贴到浏览器中,它可以正常工作。
我还注意到在调试期间,httpRequestParameters似乎根本没有任何值(显示为null)所以我猜我仍然没有以某种方式正确设置帐户参数。
我会诚实地说,我真的不是百分之百正确处理这一切并正在尝试将它们粘在一起然后让它去玩球但是我想知道我所在的部分{{1设置得当,或者我在这里遗漏了什么......
任何进一步的帮助非常感谢!
答案 0 :(得分:1)
您可以通过两种不同的方式设置BASIC身份验证凭据:
设置适当的HTTP标头:
HttpClient hc = new DefaultHttpClient();
HttpGet get = new HttpGet("http://...");
String basic_auth = new String(Base64.encodeBase64((username + ":" + password).getBytes()));
get.addHeader("Authorization", "Basic " + basic_auth);
或使用CredentialsProvider
(取决于Apache HttpComponents版本)
HttpClient hc = new DefaultHttpClient();
hc.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("username", "password"));
HttpGet get = new HttpGet ("http://...");
hc.execute(get);
答案 1 :(得分:0)
我终于设法让我的代码正常工作,最终版本如上所示。我做了一些明显的错误,例如我的域仍然设置为示例“microsoft.com”,而我实际上拼错了我的密码,除此之外它现在完全符合我的需要! :)
@vzamanillo感谢您的帮助!