2012-05-01 4 views
0

번역 된 텍스트를 가져 오기 위해 HTTP 요청을해야합니다. Internet Explorer를 통해 수동으로 수행하는 경우 속도가 빠릅니다. 두 번째 이하로 나는 결과를 얻는다.Google 번역 API : http 웹 요청을 더 빠르게 만들 수있는 방법이 있습니까?

하지만 어떤 이유로 나는 HttpWebRequest으로 처리하면 시간이 오래 걸립니다.

다음은 사용하려는 코드입니다. 그것은 잘 작동합니다. 서버에서 오류 404 (찾을 수 없음)가 표시됩니다.

누군가이 코드를 수정 해 주시겠습니까? 그들이 사용하는 인코딩이 충분한 지 확실하지 않습니다.

키가 있습니다. 여기에 게시하지 않았습니다.

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Net; 
using System.Web; 
using System.IO; 

namespace GoogleTranslateing 
{ 
    public partial class Form1 : Form 
    { 
     string apiKey = "My Key"; 
     string sourceLanguage = "en"; 
     string targetLanguage = "de"; 
     string googleUrl; 
     string textToTranslate = "hello world"; 

     public Form1() 
     { 
      InitializeComponent(); 

      googleUrl = "https://www.googleapis.com/language/translate/v2?key=" + apiKey + "&q=" + textToTranslate + "&source=" + sourceLanguage + "&target=" + targetLanguage; 

      webRequest(); 

     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 

     } 

     private void webRequest() 
     { 
      // Create a request using a URL that can receive a post. 
      WebRequest request = WebRequest.Create(googleUrl); 
      // Set the Method property of the request to POST. 
      request.Method = "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"; 
      // 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. 
      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); 
      // Clean up the streams. 
      reader.Close(); 
      dataStream.Close(); 
      response.Close(); 
     } 
    } 
} 

그리고 빨리 방법은 다음 WebRequestWebResponse를 사용하고 계십니까?

+0

디버깅 세션 당 여러 번 실행 해 보셨습니까? –

+0

그리고 코드를 통해 어떤 부분이 속도 저하를 일으키는 지 살펴 보았습니까? – Brian

+1

문제의 성능 또는 404 오류입니까? 아니면 둘다? –

답변

0

POST 데이터를 허용하지 않는 서비스로 보내려고하므로 (또한 필요하지 않음) 404 오류가 생성됩니다. 내 Google의 API 계정에 청구를 설정하지 않은

private void webRequest() 
{ 
    // Create a request using a URL that can receive a post. 
    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); 
    // Clean up the streams. 
    reader.Close(); 
    dataStream.Close(); 
    response.Close(); 
} 

다음에 당신의 webRequest()를 ... 변경; 이제는 (403) Forbidden 오류가 발생하여 이것이 완전한 수정임을 확인할 수는 없지만 시도해보십시오. 적어도 이것은 404 오류 문제를 해결합니다.