7

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

有什么方法可以处理这个 URL 并获取返回的值,而无需转到浏览器(在应用程序中处理 url)?

谢谢

4

3 回答 3

27

真的很容易:

using System.Net;

...

var response = new WebClient().DownloadString("http://test.com?id=1");
于 2013-01-15T14:47:41.617 回答
2
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();
}

这应该可以解决问题。

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

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

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

于 2013-01-15T14:44:57.580 回答
2

这是我经常用于类似目的的一个简单函数(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

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

于 2013-01-15T14:46:16.970 回答