C#:httpclient post 方法返回 StatusCode:403,ReasonPhrase:'Forbidden'

问题描述 投票:0回答:1

我使用下面的代码调用 GoogleTranslate API,但得到输出代码状态 403。 请告诉我这里缺少什么?

class MainClass
{
    var postData = new PostData
    {
        q = { "hi I am Tom","Hello how are you?"},
        target = "fr",
        format = "text",
        source = "",
        model="",
        key = "123455xxxx"
    };

    var client = new HttpClient();

    client.BaseAddress = new Uri("https://translation.googleapis.com/");

    var json = JsonSerializer.Serialize(postData);
    var content = new StringContent(json, Encoding.UTF8, "application/json");

    Console.WriteLine(content.ReadAsStringAsync().Result);

    var response = client.PostAsync("language/translate/v2/", content).Result;
    Console.WriteLine(response.ToString());
}

**输出:**

StatusCode: 403, ReasonPhrase: 'Forbidden', Version: 1.1, Content: System.Net.Http.HttpConnection+HttpConnectionResponseContent, Headers:
{
  Vary: X-Origin
  Vary: Referer
  Vary: Origin
  Vary: Accept-Encoding
  Date: Fri, 23 Aug 2024 14:24:51 GMT
  Server: ESF
  Cache-Control: private
  X-XSS-Protection: 0
  X-Frame-Options: SAMEORIGIN
  X-Content-Type-Options: nosniff
  Alt-Svc: h3=":443"; ma=2592000,h3-29=":443"; ma=2592000
  Accept-Ranges: none
  Transfer-Encoding: chunked
  Content-Type: application/json; charset=UTF-8
}

我尝试按照this在线教程来调用API。

c# post http-status-code-403
1个回答
0
投票

Http状态码

403
表示服务器确实收到了请求,但由于某种原因拒绝/拒绝了它,通常原因是身份验证失败。

话虽如此,请查明您是否获得了 API 密钥,或者是否提及了用户识别或身份验证。通常在使用外部 API 时,您将获得一个 API 密钥,用于验证您的请求。

© www.soinside.com 2019 - 2024. All rights reserved.