C# 调用POST请求

 /// 
        /// 
        /// 
        /// 为请求地址: http://127.0.0.1:8080/wms/broadcast/startAlarmTaskTTS 
        /// 请求内容 Json格式串
        /// 
        public static string PostUrl(string url, string postData)
        {
            string result = "";
            while (true)
            {
                try
                {
                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                    req.Method = "POST";
                    req.ContentType = "application/json";
                    req.Timeout = 5 * 1000;//请求超时时间
                    //req.ReadWriteTimeout = 5 * 1000;  //访问成功后读写流超时                
                    req.Credentials = new NetworkCredential("root", "root123");
                    //byte[] data = Encoding.UTF8.GetBytes(postData);
                    //req.ContentLength = data.Length;
                    using (var streamWriter = new StreamWriter(req.GetRequestStream()))
                    {
                        streamWriter.Write(postData);
                        streamWriter.Flush();
                        streamWriter.Close();                      
                    }
 
                    HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                    if (resp.StatusCode != HttpStatusCode.OK) //如果服务器未响应,那么继续等待相应
                        continue;                   
                    Stream stream = resp.GetResponseStream();
                    //获取响应内容
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        result = reader.ReadToEnd();
                    }
                }
                catch (Exception e)
                {
                     MessageBox.Show(e.Message.ToString());
                }
 
                return result;               
            }
        }

你可能感兴趣的:(C#编程语言)