首页 » C# http post和get方法

C# http post和get方法

2018/1/4 13:55:20 413 梦影雾花

HttpPost方法

public static string HttpPost(string Url, string postDataStr)
{
    byte[] postBytes = Encoding.UTF8.GetBytes(postDataStr);
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded;";
    request.ContentLength = postBytes.Length;
    StreamWriter writer = new StreamWriter(request.GetRequestStream());
    writer.Write(postDataStr);
    writer.Flush();
    writer.Close();
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    string encoding = response.ContentEncoding;
    if (encoding == null || encoding.Length < 1)
    {
        encoding = "utf-8"; //默认编码  
    }
    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
    string retString = reader.ReadToEnd();
    reader.Close();
    return retString;
}


HttpGet方法

public string HttpGet(string Url, string postDataStr)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
    request.Method = "GET";
    request.ContentType = "text/html;charset=UTF-8";

    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    Stream stream = response.GetResponseStream();
    StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("utf-8"));
    string retString = reader.ReadToEnd();
    reader.Close();
    stream.Close();

    return retString;
}


阅读延展
评论列表
新浪微博
微信