Curl -F等价于C# [英] Curl -F equivalent in C#

查看:891
本文介绍了Curl -F等价于C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在C#中使用HTTPClient对象向API发送一个post请求。
这是CURL命令:

I am trying to use HTTPClient object in C# to send a post request to an API. This is the CURL command:

curl -X POST https://zzz.zzz.zzz/yyy -F Key=abcd -F media=@"audio.aac"

我写了以下代码: / p>

I wrote the following code:

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变量中有任何问题, ?

Is there any issue in the dataContect variable or it's something else?

推荐答案

发送POST时,发送到服务器的Content-Type确实是服务器期望的。您可以从 -trace 选项发送的内容nofollow> curl

When sending a POST it is important that the Content-Type you send to server is indeed the one the server expects. You can easily verify what is send with the -trace option from curl:

curl -v --trace - -X POST http://localhost -F Key=abcd -F media=@"image.txt"

运行此操作时,在前几行的位置:

When you run this you'll find somewhere in first few lines this:

00b0: 63 6f 6e 74 69 6e 75 65 0d 0a 43 6f 6e 74 65 6e continue..Conten
00c0: 74 2d 54 79 70 65 3a 20 6d 75 6c 74 69 70 61 72 t-Type: multipar
00d0: 74 2f 66 6f 72 6d 2d 64 61 74 61 3b 20 62 6f 75 t/form-data; bou
00e0: 6e 64 61 72 79 3d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d ndary=----------
00f0: 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d ----------------
0100: 2d 2d 61 61 62 64 66 31 66 66 38 35 66 66 0d 0a --aabdf1ff85ff..
0110: 0d 0a                                           ..

所以curl发送一个Content-Type multipart / form-data;

So curl is sending an Content-Type of multipart/form-data;

在您的代码中,您使用类 FormUrlEncodedContent 其中描述:

In your code you use the class FormUrlEncodedContent which states in its description:


使用application / x-www-形式 - urlencoded MIME类型编码的名称/值元组的容器。

A container for name/value tuples encoded using application/x-www-form-urlencoded MIME type.

这不是正确的Conent-Type。

So that is not the correct Conent-Type.

匹配是 MultipartFormDataContent ,因为它声明:

A better match is the MultipartFormDataContent because it states:


提供使用multipart / form-data MIME类型编码的内容的容器。 / p>

Provides a container for content encoded using multipart/form-data MIME type.

找到正确的类,我们只需要建立容器:

With the correct classes found we only need to build up the container:

var dataContent = new MultipartFormDataContent();
var keyValue = new ByteArrayContent( Encoding.ASCII.GetBytes("abcd") );
dataContent.Add(keyValue, "key");

using (var client = new HttpClient())
{
    // open your file
    using (var fs = File.OpenRead(@"c:\path\to\audio.acc"))
    {
        // create StreamContent from the file   
        var fileValue = new StreamContent(fs);
        // add the name and meta-data 
        dataContent.Add(fileValue, "media", "audio.acc");

        HttpResponseMessage response = await client.PostAsync(
                  "http://yoursite.org", 
                  dataContent);

        HttpContent responseContent = response.Content;

        using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
        {
            Console.WriteLine(await reader.ReadToEndAsync());
        }
    }
}

运行此代码, a href =http://www.telerik.com/fiddler =nofollow> Fiddler :

Running this code reveals in Fiddler:

POST / HTTP/1.1
Content-Type: multipart/form-data; boundary="f7335f00-bc16-4518-ae7a-149491403792"
Host: yoursite.org
Content-Length: 1014
Expect: 100-continue
Connection: Keep-Alive

--f7335f00-bc16-4518-ae7a-149491403792
Content-Disposition: form-data; name=key

abcd
--f7335f00-bc16-4518-ae7a-149491403792
Content-Disposition: form-data; name=media; filename=audio.acc; filename*=utf-8''audio.acc

这更符合跟踪输出卷曲。

which is more in line with the trace output from curl.

这篇关于Curl -F等价于C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆