【问题标题】:How to call Google Cloud API using RestSharp and OAuth 2如何使用 RestSharp 和 OAuth 2 调用 Google Cloud API
【发布时间】:2016-08-04 01:46:16
【问题描述】:

我正在尝试调用谷歌云 API。具体来说,来自 c# 的语言 API 使用 RestSharp 库和 OAuth 2。我能够使用下面的 curl 调用成功连接到 API:

curl -s -k -H "Content-Type: application/json" -H "Authorization: Bearer <access_token>"
     https://language.googleapis.com/v1beta1/documents:annotateText
 -d @c:\temp\entity_request.json > c:\temp\googleanalysis.json

我尝试了几种不同的身份验证方式,但到目前为止都没有奏效。我最新的 c# 代码如下所示:

var client = new RestClient("https://language.googleapis.com");
client.Authenticator = new RestSharp.Authenticators.HttpBasicAuthenticator("client-app", "<access_token>");


var request = new RestRequest("/v1beta1/documents:analyzeEntities", Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddFile("filename", @"c:\temp\entity_request.json");

var response = client.Execute(request);
var content = response.Content;

当我从 c# 运行此调用时,我收到以下错误:

{
  "error": {
    "code": 403,
    "message": "The request cannot be identified with a client project. Please pass a valid API key with the request.",
    "status": "PERMISSION_DENIED"
  }
}

我的问题是如何正确调用 RestSharp 中的谷歌云 API,就像我使用 curl 成功的方式一样?

【问题讨论】:

    标签: c# curl oauth restsharp google-language-api


    【解决方案1】:

    这对我有用:

                //obtenemos el token para las peticiones
                string access_token = GetAccessToken(jsonFolder, new string[] { "https://www.googleapis.com/auth/cloud-platform" });
    
                //peticiones hacia el rest de automl
                var client = new RestClient("https://language.googleapis.com");
                var request = new RestRequest("v1/documents:analyzeEntities", Method.POST);
    
                request.AddHeader("Authorization", string.Format("Bearer {0}", access_token));
                request.AddHeader("Content-Type", "aplication/json");
    
                //seteamos el objeto
                var aml = new AutoMLload_entities();
                aml.document.content = text;
    
                request.AddJsonBody(aml);
                IRestResponse response = client.Execute(request);
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-07
      • 2020-03-04
      • 2020-06-29
      相关资源
      最近更新 更多