我在使用RestSharp发出POST请求时遇到问题。我的Hashtable对象'param'包含必须发布到服务器的键值对。我尝试了几种组合,并在服务器端获得了奇怪的输出。

范例1:

var client = new RestClient();
var request = new RestRequest(url, Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody (param);


输出:

Parameters: {"_json"=>[{"Key"=>"customer_subject_id", "Value"=>"300"}, {"Key"=>"client_code", "Value"=>"337"}, {"Key"=>"reservation_id", "Value"=>"9798"}, {"Key"=>"guid", "Value"=>"ODUUME4qhLmAcBVGlT4mrGbaHcbuXZID"}, {"Key"=>"customer_client_subject_id", "Value"=>"300"}, {"Key"=>"exam_code", "Value"=>"300"}, {"Key"=>"signature", "Value"=>"6bcbffb0c8ddcd89f159cf5ddd485d1eed76d1694ba329db5431f883bac3e982"}, {"Key"=>"customer_id", "Value"=>"lol"}, {"Key"=>"session_duration", "Value"=>60}]}


范例2:

var client = new RestClient();
var request = new RestRequest(url, Method.POST);
foreach(DictionaryEntry entry in param){
 request.RequestFormat = DataFormat.Json;
 request.AddParameter ((entry.Key.ToString()), entry.Value);
}


输出:

Parameters: {"customer_subject_id"=>"300", "client_code"=>"337", "reservation_id"=>"9798", "guid"=>"o9LJ5e9t52xxFhxhAoHzmYd7AiQ3nu36", "customer_client_subject_id"=>"300", "exam_code"=>"300", "signature"=>"297cd7e871df885393ebe44b262cb40b8c03e55ae1f0567ff708e9811b2aedf8", "customer_id"=>"lol", "session_duration"=>"60"}


#2的输出似乎正确,但是我在服务器端收到401。奇怪的是,GET输出与#2匹配,但是请求成功完成。我认为问题可能在于该请求总共要发布10个参数,但应该在正文中发布一个JSON格式的字符串。通常,我会在主体中放入JSON格式的字符串,但是即使使用独立的JSON序列化程序获取Hashtable的JSON字符串并将其放入AddBody时,我也会得到以下信息:

范例3:

var client = new RestClient();
var request = new RestRequest(url, Method.POST);
String paramJson = SimpleJson.SerializeObject (param);
request.RequestFormat = DataFormat.Json;
request.AddBody (paramJson);


输出:

  Parameters: {"_json"=>"[{\"Key\":\"customer_subject_id\",\"Value\":\"300\"},{\"Key\":\"client_code\",\"Value\":\"337\"},{\"Key\":\"reservation_id\",\"Value\":\"9798\"},{\"Key\":\"guid\",\"Value\":\"56ZAsFtBx7jhDmdconWTb40qGirNagxK\"},{\"Key\":\"customer_client_subject_id\",\"Value\":\"300\"},{\"Key\":\"exam_code\",\"Value\":\"300\"},{\"Key\":\"signature\",\"Value\":\"57d7c878dec24da98815071d1dc3730873285b3ae65f9d98591da94266b8f7d7\"},{\"Key\":\"customer_id\",\"Value\":\"lol\"},{\"Key\":\"session_duration\",\"Value\":60}]"}


我最奇怪的是,为什么RestSharp创建的JSON字符串的开头包含“ _json”。

谢谢,
约翰

最佳答案

您的服务器正在运行Rails吗?也许这与https://groups.google.com/forum/#!topic/rubyonrails-core/ZYBI_XHYpak有关

如果您可以控制服务器端,则最好使用AddParameter并传递一个JSON字符串,您可以在服务器端进行解析。

08-26 18:56
查看更多