当前位置 : 主页 > 编程语言 > c语言 >

c# post和get请求

来源:互联网 收集:自由互联 发布时间:2021-06-25
// summary /// 发送http post请求 /// /summary /// param name="url" 地址 /param /// param name="parameters" 查询参数集合 /param /// returns/returns public string CreatePostHttpResponse( string url, IDictionary string , string par
// <summary>
/// 发送http post请求
/// </summary>
/// <param name="url">地址</param>
/// <param name="parameters">查询参数集合</param>
/// <returns></returns>
public string CreatePostHttpResponse(string url, IDictionary<string, string> parameters)
{
    HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;//创建请求对象
    request.Method = "POST";//请求方式
    request.ContentType = "application/x-www-form-urlencoded";//链接类型
    //构造查询字符串
    if (!(parameters == null || parameters.Count == 0))
    {
        StringBuilder buffer = new StringBuilder();
        bool first = true;
        foreach (string key in parameters.Keys)
        {
 
            if (!first)
            {
                buffer.AppendFormat("&{0}={1}", key, parameters[key]);
            }
            else
            {
                buffer.AppendFormat("{0}={1}", key, parameters[key]);
                first = false;
            }
        }
        byte[] data = Encoding.UTF8.GetBytes(buffer.ToString());
        //写入请求流
        using (Stream stream = request.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }
    }
    return GetResponseString((HttpWebResponse)request.GetResponse());

}
/// <summary> /// 发送http Get请求 /// </summary> 
/// <param name="url"></param>
/// <returns></returns>
public string CreateGetHttpResponse(string url)
{
  HttpWebRequest request
= WebRequest.Create(url) as HttpWebRequest;
  request.Method
= "GET";
  request.ContentType
= "application/x-www-form-urlencoded";//链接类型
  return GetResponseString((HttpWebResponse)request.GetResponse());
}

/// <summary> /// 从HttpWebResponse对象中提取响应的数据转换为字符串 /// </summary>
/// <param name="webresponse"></param>
/// <returns></returns>
public string GetResponseString(HttpWebResponse webresponse)
{
  using (Stream s = webresponse.GetResponseStream())
{
    StreamReader reader
= new StreamReader(s, Encoding.UTF8); return reader.ReadToEnd(); } }
网友评论