美文网首页
C# POST请求demo,contentType 格式:app

C# POST请求demo,contentType 格式:app

作者: Q轩哥 | 来源:发表于2018-04-11 14:55 被阅读0次

/*

  • url:为请求地址

  • postData:请求内容例如:"key1=value1&key2=value2&key3=value3"
    */
    public static string PostUrl(string url, string postData)
    {
    string result = "";
    try
    {
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

            req.Method = "POST";
    
            req.ContentType = "application/x-www-form-urlencoded";
    
            req.Timeout = 800;//请求超时时间
    
            byte[] data = Encoding.UTF8.GetBytes(postData);
    
            req.ContentLength = data.Length;
    
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
    
                reqStream.Close();
            }
    
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
    
            Stream stream = resp.GetResponseStream();
    
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
        }catch(Exception e){}
    
        return result;
    

    }

相关文章

网友评论

      本文标题:C# POST请求demo,contentType 格式:app

      本文链接:https://www.haomeiwen.com/subject/yptzhftx.html