私は翻訳されたテキストを取得するためにHTTPリクエストを行う必要があります。 Internet Explorerで手動で実行すると高速です。秒以内に私は結果を得る。Google Translate API:httpウェブリクエストをより迅速にする方法はありますか?
しかし、もし私がHttpWebRequest
でそれをすると何らかの理由で、それははるかに時間がかかります。
ここで私が使用しようとしているコードです。それはうまくいく。サーバーからエラー404(Not Found)が表示されます。
誰かが私にこのコードを修正してもらえますか?彼らが使っているエンコーディングが十分なのかどうかもわかりません。
私はキーを持っています。ここにそれを公開していないだけです。
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エラーですか?または両方? –