我需要发出一个 HTTP 请求来取回翻译后的文本。如果我通过 Internet Explorer 手动操作,它会很快;在一秒钟或更短的时间内,我得到了结果。
但由于某种原因,如果我这样做,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
and更快的方法WebResponse
吗?