简体   繁体   中英

c# - curl equivalent for multipart form data post request

I'm making a call to third-party api. Here's the third-party api info and what they expect:

POST /api/ HTTP/1.1
Host: testurl.com
Content-Type: multipart/form-data

curl https://testurl.com/api \
     -H "Content-Type: multipart/form-data" \
     -F "document[description]=meeting notes" \
     -F "document[matter][id]=123" \
     -F "document[document_category][name]=Offers" \
     -F "document_version[last_modified_at]=2013-12-03T23:35:32+00:00" \
     -F "document_version[uploaded_data]=@test.txt"

I need to write ac# equivalent post method to send these info. I have taken care of the header in the curl call, but I'm not sure on the rest of the form-data. For instance, the "document" and "document_version" along with their respective attributes (or whatever they are), how do I pass those info along?

Here's what I found: http://www.briangrinstead.com/blog/multipart-form-post-in-c

I did exactly what's done in that link, but got back Bad Request error. More specific error:

{"error":"api error","message":"undefined method `key?' for nil:NilClass"}

I have no idea what's going on in the third-api so I don't know what this error means. Also, I'm trying to post pdf doc.

You can use the HttpClient

var client = new HttpClient();
var image = File.ReadAllBytes("c:\\test.png");
var formData = new MultipartFormDataContent();
formData.Add(new StreamContent(new MemoryStream(image)), "name","fileName.png");
formData.Add(new StringContent("content"), "name");

var response = client.PostAsync("http://localhost:5001/api/someMethod", formData).Result;

if (!response.IsSuccessStatusCode)
    {
     Console.WriteLine(response.StatusCode);
    }
    else
    {
     var content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
     Console.WriteLine(content);
    }

This works good for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM