WCF(远程服务器返回错误: 400 错误的请求)
类似相关问题有以下:
WCF- restful接口 POST方式调用报错(远程服务器返回错误: 400 错误的请求)
WCF Rest:不使用UriTemplate使用post方式传参解决HTTP400问题以及参数映射问题
等等!
具体原因参照:原创:转载请标明出处:http://www.cnblogs.com/sh91/p/3273072.html
标记自己遇到的问题原因,描述如下:
服务器接口:
[WebInvoke(Method = "*", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
string GetExptrainhist(string strjson);//入参为string类型
客户端调用:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"http://localhost:8734/GetExptrainhist");
request.ContentType = "application/json";
request.Method = "POST";
//======测试数据======start===============
ExpTrainHist_req t = new ExpTrainHist_req();
t.account = "exp";
t.fc = "expTrainHist_req";
t.starttime = "2017-04-17 13:00:00";
t.endtime = "2017-04-17 14:04:51";
string data = Newtonsoft.Json.JsonConvert.SerializeObject(t);
//string inputString = "c901411";
//======end===========
string inputString = data;
//string inputString = "{\"IdNumbr\":\"612523198308190014\",\"StuId\":\"901411\",\"SchCode\":\"1011099212\",\"TrainId\":\"3\",\"StartTime\":\"2017-04-17 00:00:01\",\"During\":\"3000\",\"ScoreHis\":\"10\"}";
Byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(inputString);
request.ContentLength = byteArray.Length;
Stream rstream = request.GetRequestStream();
rstream.Write(byteArray, 0, byteArray.Length);
rstream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();//此处报错:远程服务器返回错误: 400 错误的请求
Stream stream = response.GetResponseStream();
StreamReader SR = new StreamReader(stream);
String info = SR.ReadToEnd();
string temp = Newtonsoft.Json.JsonConvert.DeserializeObject(info).ToString();
SR.Dispose();
=====================
http://www.cnblogs.com/sh91/p/3273072.html博客的问题原因:
注意:JSON格式默认为“”引起,所以 "\"ss\""不能写为“ss”,否则还是HTTP400错误。因为未识别数据,将数据拼接到其他字节了吧。
自己的入参改为:
//首先将data的 json字符串的双引号改成单引号,再加上双引号传到服务,问题解决。
inputString = "\"" + data.Replace("\"","\'") + "\""
Byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(inputString);
request.ContentLength = byteArray.Length;
Stream rstream = request.GetRequestStream();
rstream.Write(byteArray, 0, byteArray.Length);
rstream.Close();