接近相关问题时有发生以下:

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();

 

相关文章

网站地图xml地图