Google Translate V2 cannot hanlde large text translations from C#

后端 未结 3 804
一生所求
一生所求 2020-12-11 04:56

I\'ve implemented C# code using the Google Translation V2 api with the GET Method. It successfully translates small texts but when increasing the text length and it takes 1,

3条回答
  •  醉酒成梦
    2020-12-11 05:55

    Apparently using WebClient won't work as you cannot alter the headers as needed, per the documentation:

    Note: You can also use POST to invoke the API if you want to send more data in a single request. The q parameter in the POST body must be less than 5K characters. To use POST, you must use the X-HTTP-Method-Override header to tell the Translate API to treat the request as a GET (use X-HTTP-Method-Override: GET).

    You can use WebRequest, but you'll need to add the X-HTTP-Method-Override header:

    var request = WebRequest.Create (uri);
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    request.Headers.Add("X-HTTP-Method-Override", "GET");
    
    var body = new StringBuilder();
    body.Append("key=SECRET");
    body.AppendFormat("&source={0}", HttpUtility.UrlEncode(source));
    body.AppendFormat("&target={0}", HttpUtility.UrlEncode(target));
     //--
    body.AppendFormat("&q={0}", HttpUtility.UrlEncode(text));
    
    var bytes = Encoding.ASCII.GetBytes(body.ToString());
    if (bytes.Length > 5120) throw new ArgumentOutOfRangeException("text");
    
    request.ContentLength = bytes.Length;
    using (var output = request.GetRequestStream())
    {
        output.Write(bytes, 0, bytes.Length);
    }
    

提交回复
热议问题