.net后台使用post方式对指定地址的方法传值并且获取结果的方法

     /// <summary>
        /// .net 后台 post http地址请求
        /// </summary>
        /// <param name="uri">请求地址</param>
        /// <param name="postData">请求数据</param>
        /// type=application/x-www-form-urlencoded  
        /// type=application/json;charset=UTF-8
        /// <returns></returns>
        private string PostHttpUrl(string uri, string postData)
        {
            try
            {
                byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(postData);
                HttpWebRequest objWebRequest = (HttpWebRequest)WebRequest.Create(uri); //发送地址
                objWebRequest.Method = "POST";//提交方式
                objWebRequest.ContentType = "application/json;charset=UTF-8";
                objWebRequest.ContentLength = byteArray.Length;
                using (Stream newStream = objWebRequest.GetRequestStream())
                {
                    newStream.Write(byteArray, 0, byteArray.Length); //写入参数
                    newStream.Close();
                }
                HttpWebResponse response = (HttpWebResponse)objWebRequest.GetResponse();//获取响应
                StreamReader sr = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
                return sr.ReadToEnd(); // 返回的数据
            }
            catch (Exception ex)
            {
                return "网络错误:" + ex.Message.ToString();
            }
        }

 

posted @ 2016-09-28 17:11  洛晨随风  阅读(2264)  评论(0编辑  收藏  举报