2013-11-15 185 views
1

我最近開始使用翻譯API,當我的輸入文本超過1300個字符時,我收到錯誤Too Large URL谷歌翻譯API「太大的URL」

我使用下面的代碼

 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每個請求。

回答

3

在某些時候,某人已經將您的代碼從發出POST請求更改爲進行GET。

GET將所有數據放入URL中,而不是放在請求正文中。網址有長度限制。回到使用POST,這個問題將消失。請參閱您的HTTP客戶端庫文檔以瞭解如何執行此操作。

+0

HI SLIM我搜索了一切,我無法獲取POST請求的代碼。你能幫我寫出來嗎?這將是一個很棒的幫助。 –

+0

我不明白。我搜索了「WebRequest POST」,並獲得了幾十個合適的點擊量。也許在使用翻譯之前,您需要確保您瞭解您的HTTP庫。 – slim