번역 된 텍스트를 가져 오기 위해 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();
}
}
}
그리고 빨리 방법은 다음 WebRequest
및 WebResponse
를 사용하고 계십니까?
디버깅 세션 당 여러 번 실행 해 보셨습니까? –
그리고 코드를 통해 어떤 부분이 속도 저하를 일으키는 지 살펴 보았습니까? – Brian
문제의 성능 또는 404 오류입니까? 아니면 둘다? –