c#请求Web Service 写法

 /// 
        /// 请求webservice接口
        /// 
        /// 请求地址
        /// 请求参数
        /// webservice接口返回信息
        private string RequestWebService(string url, string sendData)
        {
            string backMsg = "";
            WebResponse response = null;
            try
            {
                WebRequest httpRquest = HttpWebRequest.Create(url);
                httpRquest.Method = "POST";
                //这行代码很关键,不设置ContentType将导致后台参数获取不到值
                httpRquest.ContentType = "application/x-www-form-urlencoded;utf-8";
                byte[] dataArray = Encoding.UTF8.GetBytes(sendData);
                Stream requestStream = null;
                if (string.IsNullOrWhiteSpace(sendData) == false)
                {
                    requestStream = httpRquest.GetRequestStream();
                    requestStream.Write(dataArray, 0, dataArray.Length);
                    requestStream.Close();
                }
                response = httpRquest.GetResponse();
                Stream responseStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                backMsg = reader.ReadToEnd();
                reader.Close();
                reader.Dispose();
                requestStream.Dispose();
                responseStream.Close();
                responseStream.Dispose();
            }
            catch (Exception ex)
            {
                logger.Error("异常类型: \t" + ex.GetType());
                logger.Error("异常描述:\t" + ex.Message);
                logger.Error("异常方法:\t" + ex.TargetSite);
                logger.Error("异常堆栈:\t" + ex.StackTrace);
            }
            return backMsg;
        }

 

你可能感兴趣的:(c#,c#,webservice,接口)