使用HTTP WEB REQUEST从URL读取响应

时间:2012-07-20 06:26:21

标签: c#

我必须阅读来自http://www.subway.com/storelocator/default.aspx?zip=04416&country=USA的回复。我使用了以下代码,但没有得到所有回复。而不是它给出错误页面的响应提前谢谢。

protected void Page_Load(object sender, EventArgs e)
{

    string sUrl = "http://www.subway.com/storelocator/default.aspx?zip=04416&country=USA";
    XmlDocument rssDoc = new XmlDocument();
    XmlTextReader rssReader = new XmlTextReader(sUrl.ToString());

    WebRequest wrGETURL;
    wrGETURL = WebRequest.Create(sUrl);

    Stream objStream;
    objStream = wrGETURL.GetResponse().GetResponseStream();
    StreamReader objReader = new StreamReader(objStream, Encoding.UTF8);
    WebResponse wr = wrGETURL.GetResponse();
    Stream receiveStream = wr.GetResponseStream();
    StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
    string content = reader.ReadToEnd();
    Response.Write(content);
   }

3 个答案:

答案 0 :(得分:10)

我不知道您要对XmlTextReader做什么,因为返回的内容为html而非xml,但设置UserAgent足以获取该页面。

HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://www.subway.com/storelocator/default.aspx?zip=04416&country=USA");
req.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E)";
using (var resp = req.GetResponse())
{
    var html = new StreamReader(resp.GetResponseStream()).ReadToEnd();
}

答案 1 :(得分:2)

Stream objStream;
StreamReader objSR;
System.Text.Encoding encode = System.Text.Encoding.GetEncoding("utf-8");

string str = "http://domaninname.com/YourPage.aspx?name=" + "abc";
HttpWebRequest wrquest = (HttpWebRequest)WebRequest.Create(str);
HttpWebResponse getresponse = null;
getresponse = (HttpWebResponse)wrquest.GetResponse();

objStream = getresponse.GetResponseStream();
objSR = new StreamReader(objStream, encode, true);
string strResponse = objSR.ReadToEnd();
Response.Write(strResponse);

https://codepedia.info/send-webrequest-with-parameter-in-asp-net-c/

答案 2 :(得分:0)

在一行中,使用更简单的 vb.net(获得与 c# 相同的性能)

Return New System.IO.StreamReader(System.Net.HttpWebRequest.Create("http://urltogetthecontents.com").GetResponse().GetResponseStream()).ReadToEnd()