1

我最近开始研究 Translator API,Too Large URL当我的输入文本超过 1300 个字符时出现错误。

我正在使用下面的代码

        string apiKey = "My Key";
        string sourceLanguage = "en";
        string targetLanguage = "de";
        string googleUrl;
        string textToTranslate = 
        while (textToTranslate.Length < 1300)
        {
            textToTranslate = textToTranslate + " hello world ";
        }
        googleUrl = "https://www.googleapis.com/language/translate/v2?key=" + apiKey + "&q=" + textToTranslate + "&source=" + sourceLanguage + "&target=" + targetLanguage;

        WebRequest request = WebRequest.Create(googleUrl);
        // Set the Method property of the request to POST^H^H^H^HGET.
        request.Method = "GET"; // <-- ** You're putting textToTranslate into the query string so there's no need to use POST. **

        //// Create POST data and convert it to a byte array.
        //string postData = textToTranslate;
        //byte[] byteArray = Encoding.UTF8.GetBytes(postData);

        // Set the ContentType property of the WebRequest.
        request.ContentType = "application/x-www-form-urlencoded";

        // ** Commenting out the bit that writes the post data to the request stream **

        //// Set the ContentLength property of the WebRequest.
        //request.ContentLength = byteArray.Length;
        //// Get the request stream.
        //Stream dataStream = request.GetRequestStream();
        //// Write the data to the request stream.
        //dataStream.Write(byteArray, 0, byteArray.Length);
        //// Close the Stream object.
        //dataStream.Close();

        // Get the response.
        WebResponse response = request.GetResponse();
        // Display the status.
        Console.WriteLine(((HttpWebResponse)response).StatusDescription);
        // Get the stream containing content returned by the server.
        Stream dataStream = response.GetResponseStream();
        // Open the stream using a StreamReader for easy access.
        StreamReader reader = new StreamReader(dataStream);
        // Read the content.
        string responseFromServer = reader.ReadToEnd();
        // Display the content.
        Console.WriteLine(responseFromServer);
        Console.WriteLine(i);
        // Clean up the streams.
        reader.Close();
        dataStream.Close();
        response.Close();

您能否建议我可以在我的代码中进行哪些更改,以便输入文本限制可以增加到每个请求 40k - 50k。

4

1 回答 1

3

在某些时候,有人将您的代码从发出 POST 请求更改为发出 GET。

GET 将所有数据放入 URL,而不是将其放入请求正文中。URL 有长度限制。回到使用 POST,这个问题就会消失。请参阅您的 HTTP 客户端库的文档以了解如何执行此操作。

于 2013-11-15T07:27:40.447 回答