C# 处理 URL 并获取数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14340136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:31:04  来源:igfitidea点击:

Process URL and Get data

c#.netvb.netwinforms

提问by huMpty duMpty

I have a URLwhich returns array of data. For example if I have the URL http://test.com?id=1it will return values like 3,5,6,7etc…

我有一个URL返回数据数组。例如,如果我有 URL http://test.com?id=1,它将返回诸如3,5,6,7等的值……

Is there any way that I can process this URL and get the returned values without going to browser (to process the url within the application)?

有什么方法可以处理此 URL 并获取返回值而无需访问浏览器(以处理应用程序中的 url)?

Thanks

谢谢

采纳答案by Dave Bish

Really easy:

真的很简单:

using System.Net;

...

...

var response = new WebClient().DownloadString("http://test.com?id=1");

回答by jAC

string urlAddress = "YOUR URL";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
  Stream receiveStream = response.GetResponseStream();
  StreamReader readStream = null;
  if (response.CharacterSet == null)
    readStream = new StreamReader(receiveStream);
  else
    readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
  string data = readStream.ReadToEnd();
  response.Close();
  readStream.Close();
}

This should do the trick.

这应该可以解决问题。

It returns the html source code of the homepage and fills it into the string data.

它返回主页的 html 源代码并将其填充到string data.

You can use that string now.

您现在可以使用该字符串。

Source: http://www.codeproject.com/Questions/204778/Get-HTML-code-from-a-website-C

来源:http: //www.codeproject.com/Questions/204778/Get-HTML-code-from-a-website-C

回答by xfx

This is a simple function I constantly use for similar purposes (VB.NET):

这是一个我经常用于类似目的的简单函数(VB.NET):

Public Shared Function GetWebData(url As String) As String
    Try
        Dim request As WebRequest = WebRequest.Create(url)
        Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
        Dim dataStream As Stream = response.GetResponseStream()
        Dim readStream As StreamReader = New StreamReader(dataStream)
        Dim data = readStream.ReadToEnd()
        readStream.Close()
        dataStream.Close()
        response.Close()
        Return data
    Catch ex As Exception
        Return ""
    End Try
End Function

To use it, pass it the URL and it will return the contents of the URL.

要使用它,请将 URL 传递给它,它将返回 URL 的内容。