[英]C# WebClient OpenRead url
So I have this program that fetches a page using a short link (I used Google url shortener). 所以我有这个程序使用短链接获取页面(我使用谷歌网址缩短器)。 To build my example I used code from Using WebClient in C# is there a way to get the URL of a site after being redirected?
为了构建我的示例,我使用了C#中使用WebClient的代码, 有没有办法在重定向后获取站点的URL?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
MyWebClient client = new MyWebClient();
client.OpenRead("http://tinyurl.com/345yj7x");
Uri uri = client.ResponseUri;
Console.WriteLine(uri.AbsoluteUri);
Console.Read();
}
}
class MyWebClient : WebClient
{
Uri _responseUri;
public Uri ResponseUri
{
get { return _responseUri; }
}
protected override WebResponse GetWebResponse(WebRequest request)
{
WebResponse response = base.GetWebResponse(request);
_responseUri = response.ResponseUri;
return response;
}
}
}
I do not understant a thing: when I do client.OpenRead("http://tinyurl.com/345yj7x");
我不明白一件事:当我做
client.OpenRead("http://tinyurl.com/345yj7x");
时client.OpenRead("http://tinyurl.com/345yj7x");
this downloads the page that the url points to? 这会下载网址指向的页面吗? If this method downloads the page, I need something to get me only the url, so if there's a method to get only some headers, or only the url, please let me know.
如果这个方法下载页面,我需要一些东西才能得到我的网址,所以如果有方法只获取一些标题,或只有网址,请告诉我。
You can get the headers only using a HEAD request, like this: 您只能使用HEAD请求获取标头,如下所示:
var request = WebRequest.Create(sourceUri);
request.Method = "HEAD";
var response = request.GetResponse();
if (response != null) {
// You can now use response.Headers to get header info
}
Create a HttpWebRequest with the AllowAutoRedirect property set to false, then look at the Location header on the response. 创建一个将AllowAutoRedirect属性设置为false的HttpWebRequest ,然后查看响应上的Location标头。
var request = (HttpWebRequest) WebRequest.Create("http://tinyurl.com/345yj7x");
request.AllowAutoRedirect = false;
var response = request.GetResponse();
var location = response.Headers[HttpResponseHeader.Location];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.