如何获取重定向后的url

2022-04-16 教育 167阅读
publicstaticstringGetHtml(stringurl)
{
HttpWebRequestrequest=null;
HttpWebResponseresponse=null;
StreamReaderreader=null;

//因为只要读标识,标识是Guid,所以用ASCII编码,不在乎乱码
Encodingencoded=Encoding.ASCII;

try
{
request=(HttpWebRequest)WebRequest.Create(url);
request.Timeout=1000*20;
request.AllowAutoRedirect=false;

response=(HttpWebResponse)request.GetResponse();
if(response.StatusCode==HttpStatusCode.OK&&response.ContentLength<1024*1024)
{
if(response.ContentEncoding!=null&&response.ContentEncoding.Equals("gzip",StringComparison.InvariantCultureIgnoreCase))
reader=newStreamReader(newGZipStream(response.GetResponseStream(),CompressionMode.Decompress),encoded);
else
reader=newStreamReader(response.GetResponseStream(),encoded);
stringhtml=reader.ReadToEnd();

returnhtml;
}

if((response.StatusCode==HttpStatusCode.Found)||
(response.StatusCode==HttpStatusCode.Redirect)||
(response.StatusCode==HttpStatusCode.Moved)||
(response.StatusCode==HttpStatusCode.MovedPermanently))
{
returnHttpStatusCode.Redirect.ToString();
}

}
catch(Exceptionex)
{
//Logger.Error("发送请求时错误:URL:"+url+ex);
returnstring.Empty;
}
finally
{

if(response!=null)
{
response.Close();
response=null;
}
if(reader!=null)
reader.Close();

if(request!=null)
request=null;
}

returnstring.Empty;
}
声明:你问我答网所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流。若您的权利被侵害,请联系fangmu6661024@163.com