发布 RestSharp Google API 错误



我正在尝试使用RestSharp访问YouTube API。在开机自检时,我收到错误代码:400,原因如下:"此 API 不支持解析表单编码的输入"。下面是我的一小段代码:

var client = new RestClient("https://www.googleapis.com");
var request = new RestRequest(Method.POST);
request.Resource = "youtube/v3/liveBroadcasts";
request.RequestFormat = DataFormat.Json;
request.AddParameter("part", "snippet,status");
request.AddParameter("key", "MyClientId");
request.AddHeader("Authorization", "Bearer " + "MyAccessCode");
request.AddHeader("Content-Type", "application/json; charset=utf-8");
request.AddBody(aJson);
try
{
var response = client.Execute(request);
Console.WriteLine(response.Content);
}
catch (Exception e)
{
Console.WriteLine(e);
} 

上述响应内容为"此 API 不支持解析表单编码输入"在我发送的 Json 中 (aJson) 看起来像这样:

{
"snippet": {
"scheduledEndTime": "2015-01-10T12:11:11.0+0400",
"scheduledStartTime": "2015-01-10T11:11:11.0+0400",
"title": "MyBroadcastName"
},
"kind": "youtube#liveBroadcast",
"status": {
"privacyStatus": "private"
}
}

我很乐意获得与上述请求相关的任何帮助。我做错了什么?

谢谢R.

问题在于您对request.AddParameter的调用。您希望这些附加的URL作为查询参数,但是当HTTP方法为POST时,默认情况下,RestSharp会将它们作为URL编码的表单数据发送。你想要这样的东西:

request.Resource = "youtube/v3/liveBroadcasts?part={part}&key={key}";
request.AddParameter("part", "snippet,status", ParameterType.UrlSegment);
request.AddParameter("key", "MyClientId", ParameterType.UrlSegment);

感谢托德,经过一些额外的挖掘,我发现了问题。以下是固定代码:

var client = new RestClient("https://www.googleapis.com");
var request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
request.Resource = "youtube/v3/liveBroadcasts?part={part}&key={key}";
request.AddParameter("part", "snippet,status", ParameterType.UrlSegment);
request.AddParameter("key", "MyClientId", ParameterType.UrlSegment);
request.AddHeader("Authorization", "Bearer " + "MyAccessCode");
request.AddHeader("Content-Type", "application/json; charset=utf-8");
request.AddBody(anObject); //<== Here you should use an object and NOT a json. RestSharp will do the serialization!
try
{
var response = client.Execute(request);
Console.WriteLine(response.Content);
}
catch (Exception e)
{
Console.WriteLine(e);
} 

感谢您的帮助。R.

相关内容

  • 没有找到相关文章

最新更新