如何以编程方式检测网页的GET请求的来源? (C#)

时间:2017-01-19 15:10:12

标签: c# get webclient url-redirection

简而言之,我需要以编程方式检测网页的GET请求。

长期以来,我的公司目前正在尝试为安装另一部分软件的专有软件编写一个小型安装程序。

要获得这个其他软件,我意识到它就像通过C#的可爱WebClient类调用下载链接一样简单(Dir只是AppData / Local中的Temp目录):

using (WebClient client = new WebClient())
{
    client.DownloadFile("[download link]", Dir.FullName + "\\setup.exe");
}

但是,安装程序来自的页面不是直接下载页面。实际的下载链接可能会发生变化(我们公司的特定安装程序可能会在另一个下载服务器上托管)。

为了解决这个问题,我意识到我只能监控页面发出的GET请求并从那里动态获取URL。

所以,我知道我会这样做,但我只是想知道,是否有一种内置的语言部分可以让你看到页面的要求是什么?或者我是否必须自己编写此功能,这将是一个很好的起点?

2 个答案:

答案 0 :(得分:1)

我想我会这样做。首先下载下载页面的HTML内容(包含下载文件的链接的页面)。然后刮取HTML以查找下载链接URL。最后,从已删除的地址下载文件。

using (WebClient client = new WebClient())
{
    // Get the website HTML.
    string html = client.DownloadString("http://[website that contains the download link]");

    // Scrape the HTML to find the download URL (see below).

    // Download the desired file.
    client.DownloadFile(downloadLink, Dir.FullName + "\\setup.exe");
}

要从网站上抓取下载网址,我建议您使用HTML Agility Pack。有关入门的信息,请参阅here

答案 1 :(得分:-1)

我认为你必须编写自己的" mediahandler",它会返回一个HttpResponseMessage。

e.g。使用webapi2

[HttpGet]
[AllowAnonymous]
[Route("route")]
public HttpResponseMessage GetFile([FromUri] string path)
{
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    result.Content = new StreamContent(new FileStream(path, FileMode.Open, FileAccess.Read));
    string fileName = Path.GetFileNameWithoutExtension(path);
    string disposition = "attachment";
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue(disposition) { FileName = fileName + Path.GetExtension(absolutePath) };
    result.Content.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(Path.GetExtension(path)));
    return result;
}