发布RestSharp Google API错误

时间:2015-01-07 15:26:48

标签: json google-api restsharp

我正在尝试使用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.

2 个答案:

答案 0 :(得分:3)

问题在于您拨打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);

答案 1 :(得分:2)

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

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上。