【发布时间】:2016-07-28 06:16:48
【问题描述】:
我正在尝试使用 C# 中的 HTTPClient 对象向 API 发送发布请求。 这是 CURL 命令:
curl -X POST https://zzz.zzz.zzz/yyy -F Key=abcd -F media=@"audio.aac"
我写了以下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.IO;
using System.Net.Http.Headers;
namespace Speech2Text
{
class Program
{
static void Main(string[] args)
{
curl().Wait();
}
static async Task curl()
{
var client = new HttpClient();
//Create List of KeyValuePairs
List<KeyValuePair<string, string>> bodyProperties = new List<KeyValuePair<string, string>>();
bodyProperties.Add(new KeyValuePair<string, string>("key", "abcd"));
bodyProperties.Add(new KeyValuePair<string, string>("media", "@audio.aac"));
var dataContent = new FormUrlEncodedContent(bodyProperties.ToArray());
HttpResponseMessage response = await client.PostAsync("https://zzz.zzz.zzz/yyy", dataContent);
HttpContent responseContent = response.Content;
using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
Console.WriteLine(await reader.ReadToEndAsync());
}
}
}
}
但我不断得到这个:
{"code":400,"message":"Please use [media] for the media file field name in your POST request."}
dataContect 变量是否有任何问题或其他问题?
【问题讨论】:
-
@w0lf 感谢您的评论。我在上面的代码中使用了相同的方法,但我认为它没有捕获我传递给 HTTP 请求的参数。因为,在发送
media参数的同时,它并不理解。 -
问题出在服务器端,而不是客户端。你的代码没问题。你已经得到了 JSON 响应。
-
尝试从“@audio.aac”中删除“@”
-
@x... 没用。这是我应该传递的文件的名称。它不应该是文件对象或类似的东西而不是字符串吗?
-
当使用 curl 时,
@会吞下文件的内容。您将不得不手动打开文件流并将其拉入字节数组或类似的东西
标签: c# curl http-post multipartform-data dotnet-httpclient