DeepL Simulator 是一个很好的起点:https ://www.deepl.com/docs-api/simulator
使用 POST 时,auth_key它只是表单字段中的另一个字段,而不是标题。
因为内容类型是指定的,因为x-www-form-urlencoded您希望将数据作为url 编码形式发送,而不是 JSON。在电线上,这应该看起来像:
auth_key=[yourAuthKey]&text=Hello, world&target_lang=JA
下面展示了如何使用 HttpClient 从 C# 发送这个 POST 请求:
string authKey = "~MyAuthKey~";
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");
Dictionary<string, string> data = new Dictionary<string, string>
{
{ "auth_key", authKey },
{ "text", strData.Trim() },
{ "target_lang", "JA" }
};
var response = await client.PostAsync("https://api-free.deepl.com/v2/translate",
new System.Net.Http.FormUrlEncodedContent(data));
response.EnsureSuccessStatusCode();
var json = response.Content.ReadAsStringAsync().Result;
deeplResponseObj = Newtonsoft.Json.JsonConvert.DeserializeObject<DeepResponse>(json);
foreach(var tx in deeplResponseObj.translations)
Console.WriteLine("\"{0}\" (from {1})", tx.text, tx.detected_source_language);
以下类定义有助于响应的反序列化:
public class DeepResponse
{
List<DeepTranslation> translations { get;set; } = new List<DeepTranslation>();
}
public class DeepTranslation
{
public string detected_source_language { get;set; }
public string text { get;set; }
}