首页  »   Web Service

用REST方式访问wcf服务,post时老报“远程服务器返回异常: (400) 异常的请求”

网友分享于:2015-09-17  浏览:0次
用REST方式访问wcf服务,post时老报“远程服务器返回错误: (400) 错误的请求”
先贴代码

string id = "12qwsfsfasfsaf";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://xxx/GetProduct.svc/GetStudentById");

            System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
            request.Method = "POST";

            request.ContentType = "application/json";
            request.Accept = "application/json";

            request.ContentLength = Encoding.UTF8.GetByteCount(id);

            Stream myRequestStream = request.GetRequestStream();

            StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));

            myStreamWriter.Write(id);

            myStreamWriter.Close();

            //HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            HttpWebResponse response;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response = (HttpWebResponse)ex.Response;
            } 
            StreamReader sr = new StreamReader(response.GetResponseStream());
            string jsonstr = sr.ReadToEnd();


奇葩的是只要参数是以数字开头的就不会报错,反之就报错,有谁遇到过这个问题没?
------解决思路----------------------
 request.ContentLength = Encoding.UTF8.GetByteCount(id);
             Stream myRequestStream = request.GetRequestStream();
             StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));

你计算长度的时候用UTF8,而实际写入时用gb2312,可能会造成问题。

改成这样试一试


byte[] bytes = Encoding.UTF8.GetBytes(id);
//如果想用gb2312就使用
// byte[] bytes = Encoding.GetEncoding("gb2312").GetBytes(id);
 request.ContentLength = bytes.Length;
Stream myRequestStream = request.GetRequestStream();
myStreamWriter.Write(bytes, 0, bytes.Length);
myStreamWriter.Close();

相关解决方案

最新解决方案