I have recently started working on Translator API and I am getting the ERROR Too Large URL when my input text exceeds 1300 characters.

I am using the below code

        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();

Can You please suggest me that what kind of changes i can do in my code, so that the input text limit can be increased unto 40k - 50k per request.

有帮助吗?

解决方案

At some point someone has changed your code from making a POST request to making a GET.

GET puts all the data into the URL instead of putting it in the request body. URLs have a length limit. Go back to using POST and this problem will go away. Refer to the documentation for your HTTP client library to find out how to do this.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top