首页 > 解决方案 > 多部分/格式数据请求

问题描述

我需要为验证码识别 API 创建多部分/表单数据请求。在 API 描述页面上,我找到了请求模板:

<form method="post" action="https://captchasiteapi.com/in.php" enctype="multipart/form-data">
<input type="hidden" name="method" value="post">
Your key:
<input type="text" name="key" value="YOUR_APIKEY">
Captcha file:
<input type="file" name="file">
<input type="submit" value="Upload and get ID">
/<form>

我基于HttpClient写了这个方法:

private async Task<string> UploadRequestAsync(string url, string filePath, string profileApiKey)
{
    var client = new HttpClient();
    var formData = new MultipartFormDataContent();
    var filestream = new FileStream(filePath, FileMode.Open);
    var fileName = Path.GetFileName(filePath);
    formData.Add(new StringContent("post"), "hidden", "method");
    formData.Add(new StringContent(profileApiKey), "key");
    formData.Add(new StreamContent(filestream), "file", fileName);
    formData.Add(new StringContent("Upload and get ID"), "submit");
    var response = await client.PostAsync(url, formData);
    if (!response.IsSuccessStatusCode){
        return null;
    }
    return await response.Content.ReadAsStringAsync();
}

但真的不知道如何创建<input type="hidden" name="method" value="post">线。如何在表单中创建 3 个值?API 的结果是类似“OK|CaptchaValue”的字符串,所以Task<string>应该没问题。

标签: c#apihttpclientmultipartform-data

解决方案


推荐阅读