如何从URL获取数据类型
本文关键字:获取 数据类型 URL | 更新日期: 2023-09-27 18:25:41
在实现了简单下载程序的基本版本后,我花了几个小时在谷歌上搜索,以了解如何获得我的URL类型,比如.mp3、.mp4等。对于daily motion等网站,谁的URL末尾没有附加它。这是因为我的下载程序适用于这些类型,但没有特定类型的链接可以下载Kb的文件,而无需播放。
以下是确定内容类型的代码,以决定下载的扩展名:
WebClient myWebClient = new WebClient();
string datastring = myWebClient.DownloadString("http://www.dailymotion.com/video/x1viyeu_pakistani-actress-meera-reema-saima-dance-on-faisal-ahmed-music-album-launch_news");
NameValueCollection headers = myWebClient.ResponseHeaders;
foreach (string key in headers.AllKeys)
{
Console.WriteLine("Header:{0},Value:{1}", key, headers[key]);
}
它向我返回了控制台上的输出列表,其中一行是:
标题:内容类型,值:text/html;charset=utf-8
现在我想知道这将如何帮助我解决已经描述的问题。
建议请
这是下载的代码
private void downloadbtn_Click(object sender, EventArgs e)
{
WebClient myWebClient = new WebClient();
//Declarations for string objects
string downloadURL, path;
//raw URL taken from user
downloadURL = this.downloadURL.Text;
path = this.savePath.Text;
Uri tmp = new Uri(downloadURL);
string EndPathFileName = tmp.Segments.Last();
path = path + @"'" + EndPathFileName;
//downloads file using async method
myWebClient.DownloadFileAsync(tmp, path);
downloadbtn.Text = "Download Started";
downloadbtn.Enabled = false;
myWebClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
myWebClient.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
}
通常有一个Content-Type
标头,它可以提示您需要什么文件类型。
很多时候,服务器也会提供有关文件名的信息——请参阅本SO,了解在(PHP)服务器端通常是如何完成的。
根据http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html#sec7.2.1
Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body.
您可以获得一个内容类型并将其拆分为:
var request = HttpWebRequest.Create("http://www.google.com") as HttpWebRequest;
if (request != null)
{
var response = request.GetResponse() as HttpWebResponse;
string contentType = "";
if (response != null)
contentType = response.ContentType;
int start = contentType.IndexOf('/');
int end = contentType.IndexOf(';', start);
string yourext = contentType.Substring(start+1, (end - start)-1);//like mp3,png,txt
}