如何使用正文选项表单数据进行发布请求

时间:2020-06-29 13:33:01

标签: c# asp.net-core

没有人知道如何将以下Postman POST Body表单数据参数转换为C#POST请求,我在末尾使用HttpClient和Web请求尝试了很多,但是它不起作用。

enter image description here

示例代码:

var bytes = (dynamic)null;
using (HttpClient httpClient = new HttpClient())
 {
    using (var multiPartContent = new MultipartFormDataContent())
    {
        var fileContent = new ByteArrayContent(documentData);
    
        //Add file to the multipart request
        multiPartContent.Headers.Add("format_source", FORMAT_SOURCE);
        multiPartContent.Headers.Add("format_target", FORMAT_TARGET);
        multiPartContent.Add(fileContent);
    
        //Post it
        bytes = httpClient.PostAsync(CONVERSION_URL, multiPartContent).Result;
    }
}

邮递区号: C#RestSharp:

var client = new RestClient("http://test-service-staging.test.com/convert");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddFile("input", "/C:/Users/DR-11/Downloads/response_1592912235925.xml");
request.AddParameter("format_source", "abc");
request.AddParameter("format_target", "xyz");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

HTTP:

POST /convert HTTP/1.1
Host: test-service-staging.test.com
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="input"; filename="/C:/Users/DR-11/Downloads/response_1592912235925.xml"
Content-Type: text/xml

(data)
----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="format_source"

abc
----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="format_target"

xyz
----WebKitFormBoundary7MA4YWxkTrZu0gW

卷曲:

curl --location --request POST 'http://test-service-staging.test.com/convert' \
--form 'input=@/C:/Users/DR-11/Downloads/response_1592912235925.xml' \
--form 'format_source=abc' \
--form 'format_target=xyz'

需要传递API中的字节来代替文件路径。

1 个答案:

答案 0 :(得分:0)

好,这是您使用HttpClient的邮递员请求的示例。
如果没有实时网址,很难对此进行测试,但这有望对您有所帮助。

不确定是否要为返回类型使用字符串或字节数组,我选择了一个字符串,但是如果您确实想要字节数组,则应使用类似的方法

static async System.Threading.Tasks.Task<byte[]> SendDataAsync()
return await httpResponseMessage.Content.ReadAsByteArrayAsync();

    static async System.Threading.Tasks.Task Main(string[] args)
    {
        // Is This Returning A String Or Bytes
        string responseAsString = await SendDataAsync();
        Console.ReadKey();
    }

    static async System.Threading.Tasks.Task<string> SendDataAsync()
    {
        using (HttpClient httpClient = new HttpClient())
        using (MultipartFormDataContent formDataContent = new MultipartFormDataContent())
        {
            // Create Form Values
            KeyValuePair<string, string>[] keyValuePairs = new[]
            {
                new KeyValuePair<string, string>("format_source", "abc"),
                new KeyValuePair<string, string>("format_target", "xyz")
            };

            // Loop Each KeyValuePair Item And Add It To The MultipartFormDataContent.
            foreach (var keyValuePair in keyValuePairs)
            {
                formDataContent.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
            }

            // Get The ByteArrayContent,Reading Bytes From The Give File Path.
            // Adding It To The MultipartFormDataContent Once File Is Read.
            string filePath = @"C:\Users\andrew.eberle\Desktop\data.xml";
            ByteArrayContent fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(filePath));

            // Add Content Type For MediaTypeHeaderValue.
            fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

            // Add The File Under ''input'
            formDataContent.Add(fileContent, "input", System.IO.Path.GetFileName(filePath));

            // Post Request And Wait For The Response.
            HttpResponseMessage httpResponseMessage = await httpClient.PostAsync("http://test-service-staging.test.com/convert", formDataContent);

            // Check If Successful Or Not.
            if (httpResponseMessage.IsSuccessStatusCode)
            {
                // Return Byte Array To The Caller.
                return await httpResponseMessage.Content.ReadAsStringAsync();
            }
            else
            {
                // Throw Some Sort of Exception?
                return default;
            }
        }
    }