Skip to content

Instantly share code, notes, and snippets.

@pocari
Created November 8, 2012 13:55
Show Gist options
  • Save pocari/4038944 to your computer and use it in GitHub Desktop.
Save pocari/4038944 to your computer and use it in GitHub Desktop.
basic認証のサイトからファイルをダウンロードするサンプル
var BASIC_AUTH_USER = "tomcat";
var BASIC_AUTH_PASS = "tomcat";
var URL_PREFIX = "http://localhost:8080";
//------------------------------------------------------------
var HTTPREQUEST_SETCREDENTIALS_FOR_SERVER = 0;
var adTypeBinary = 1;
var adSaveCreateOverWrite = 2;
var HTTP_OK = 200;
function gen_url(path) {
return URL_PREFIX + path;
}
function get_response(url) {
var http = new ActiveXObject("WinHttp.WinHttpRequest.5.1");
http.open("GET", url, false);
http.SetCredentials(BASIC_AUTH_USER, BASIC_AUTH_PASS, HTTPREQUEST_SETCREDENTIALS_FOR_SERVER);
http.Send();
if (http.Status != HTTP_OK) {
return null;
}
return http;
}
function save_response(path, data) {
var ado_stream = new ActiveXObject("ADODB.Stream");
ado_stream.Type = adTypeBinary;
ado_stream.Open;
ado_stream.Write(data);
ado_stream.SaveToFile(path, adSaveCreateOverWrite);
ado_stream.Close;
}
function get_file_list() {
var ret = get_response(gen_url("/hello"));
var match_data = ret.ResponseText.match(/a href="(.+.zip)"/g);
var file_list = []
if (match_data) {
for (var i = 0; i < match_data.length; i++) {
var reg = new RegExp("\"", "g"); //インデント崩れるのでRegExpで。
file_list.push(match_data[i].replace(reg, "").replace("a href=", ""));
}
}
return file_list;
}
function basename(filename) {
filename.match(/.*\/(.*)$/); //絶対にマッチするのでmatchだけ
return RegExp.$1;
}
function main() {
var files = get_file_list();
for (var i = 0; i < files.length; i++) {
var file = files[i];
var url = gen_url(file);
var result = get_response(url);
var save_filename = "./" + basename(file);
if (result) {
save_response(save_filename, result.responseBody);
WSH.echo(url + " was downloaded as " + save_filename);
} else {
WSH.echo(url + " was failed to be downloaded.");
}
}
}
WSH.echo(main());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment