You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

向DeepL API发送HttpPost请求上传HTML文件遇400错误求助

向DeepL API上传HTML文件时出现400 Bad Request错误排查

问题描述

上传HTML文件至DeepL API时持续返回400 Bad Request错误,需排查原因并解决。

相关信息

代码片段

string uploadFilePath = htmlfile.FullName;    // 从FileInfo获取的完整路径

文件路径

C:\Users\username\AppData\Local\Temp\6af93935-6e76-4222-b12f-2e21d350b4da\wfujwrv5.5t3.html(后缀为.html)

完整请求代码

string apiBaseAddress = "https://api.deepl.com/v2/document";
string fileContentType = "application/x-www-form-urlencoded"; // "text/html";
using (var client = new HttpClient())
{
    var values = new[]
    {
        new KeyValuePair<string,string>("auth_key",key),
        new KeyValuePair<string,string>("target_lang",target_lang), // 当前设为DE
    };
    using var content = new MultipartFormDataContent();
    foreach (var val in values)
    {
        content.Add(new StringContent(val.Value), val.Key);
    }
    var fileContent = new StreamContent(new FileStream(uploadFilePath, FileMode.Open));

    fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(fileContentType);

    fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = uploadFilePath };
   
    content.Add(fileContent);

   
    //client.BaseAddress = new Uri(apiBaseAddress);
    var result = client.PostAsync(apiBaseAddress, content).Result; // 抛出Bad Request 400错误
}

HTML文件内容

<!DOCTYPE html>
   <html>
     <head></head>
       <body>
           <strong>
            ItemName 101
           </strong> 
           -Description about the item
           <br />
           <br /> Testing 101 
        </body>
    </html>

报错信息

{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  transfer-encoding: chunked
  access-control-allow-origin: *
  x-trace-id: 7da3ba4922486baed9aa109dbb97ce50
  strict-transport-security: max-age=63072000; includeSubDomains; preload
  server-timing: l7_lb_tls;dur=106, l7_lb_idle;dur=0, l7_lb_receive;dur=79, l7_lb_total;dur=195
  access-control-expose-headers: Server-Timing
  Date: Mon, 24 Apr 2023 12:17:13 GMT
  Content-Type: application/json; charset=utf-8
  Content-Length: 32
}}

排查与修复要点

  • 修正文件Content-Type:当前代码错误使用application/x-www-form-urlencoded作为文件类型,需改为text/html,取消注释代码中正确的类型值即可。
  • 指定文件参数名:DeepL API要求上传文件的参数键为file,需将content.Add(fileContent)改为content.Add(fileContent, "file"),否则API无法识别上传的文件。
  • 优化FileName设置:当前FileName设为完整文件路径,建议仅保留文件名(如wfujwrv5.5t3.html),避免路径中的特殊字符引发解析异常。
  • 调整异步调用方式:使用.Result同步阻塞调用可能导致死锁,建议改用await client.PostAsync(apiBaseAddress, content),并将方法标记为async。
  • 获取详细错误信息:400错误的响应内容包含JSON格式的具体错误描述,可通过var errorMsg = await result.Content.ReadAsStringAsync();读取,精准定位问题。

内容的提问来源于stack exchange,提问作者user3920526

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 01:45:32