3

我在使用 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”。

谢谢,约翰

4

1 回答 1

1

你的服务器运行 Rails 吗?也许这是相关的https://groups.google.com/forum/#!topic/rubyonrails-core/ZYBI_XHYpak

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

于 2017-12-07T00:12:49.577 回答