C#实现的HttpGet请求

时间:2023-03-08 20:01:45

话不多说,代码贴上:

/// <summary>
/// HTTP Get请求
/// </summary>

/// <param name="url">API地址</param>

/// <param name="encode">编码</param>

public static String GetData(String url, Encoding encode)
{

  HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  request.Method = "GET";
  request.ContentType = "text/html, application/xhtml+xml, */*";

  HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  Stream rs = response.GetResponseStream();
  StreamReader sr = new StreamReader(rs, encode);
  var result = sr.ReadToEnd();
  sr.Close();
  rs.Close();
  return result;

}

传入我们需要的API地址,以及得到结果的编码,如Encoding.UTF-8;

对于Get请求比较简单,首先创建HttpWebRequest对象:

调用传入的Url

设置请求方式 如:Method = "GET"  ;

请求的内容格式  如:.ContentType = "text/html, application/xhtml+xml, */*";(不熟悉的小伙伴可以看这里的对照表:http://tool.oschina.net/commons )

然后获取响应内容,通过流对象StreamReader保存,再根据我们所需的编码(如:Encoding.UTF-8)解读出来即可。

以及别忘了导入命名空间using System.IO;和using System.Net;。