简体   繁体   中英

How to make PostAsync request with HttpClient to send/upload CSV file?

I am making a PostAsync API call with HttpClient to send/upload a CSV file.I have equivalent code in PHP, that works fine. But when I try it in C# gives me "Internal Server Error" with status code 500.Below is the c# code that I have tried.

  string apiUrl = "https://api.host/csv-upload/api-key?remove-hosts=false";

            HttpClient client = new HttpClient();

            //Prepare request header
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
            client.DefaultRequestHeaders.Add("Api-Key", "xxxyyyzzz");


            //cache
            CacheControlHeaderValue cacheControl = new CacheControlHeaderValue();
            cacheControl.NoCache = true;
            client.DefaultRequestHeaders.CacheControl = cacheControl;

            byte[] bytes = File.ReadAllBytes(csvFilePath); //c://Temp/test.csv
            HttpContent fileContent = new ByteArrayContent(bytes);
            fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("text/csv");

            MultipartFormDataContent content = new MultipartFormDataContent();
            content.Add(fileContent, "file", "test.csv");

            try
            {
                string message = client.PostAsync(new Uri(apiUrl), content).ContinueWith(async responseTask =>
                {
                    HttpResponseMessage response = await responseTask;

                    return response.Content.ReadAsStringAsync().ContinueWith(async contentTask =>
                    {
                        string contents = await contentTask;
                        return contents;
                    }).Result.Result;
                }).Result.Result;


            }
            catch(Exception ex)
            {
                string message = ex.Message;
                Console.WriteLine(message); ;
            }
            finally
            {
                Console.WriteLine("Error");
            }

I expect the status code 202 when calling the api.

But the actual result is "Internal server error" .

Equivalent PHP code that works fine is:

function api_call($url, $api_key, $csv_file) {

   $request = new \Http_Request2($url);

   $request->setHeader(array(
        'Api-Key' => $api_key,
       'content-type'  => 'application/x-www-form-urlencoded'
   ));

   $request->setMethod(\HTTP_Request2::METHOD_POST);
   $request->addUpload('file' , $csv_file , 'file' , 'text/csv');
   $response = $request->send();

   return $response->getBody();
}

Try below code

string apiUrl = "https://api.host/csv-upload/api-key?remove-hosts=false;

            HttpClient client = new HttpClient();

            //Prepare request header
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
            client.DefaultRequestHeaders.Add("Api-Key", "xxxyyyzzz");


            //cache
            CacheControlHeaderValue cacheControl = new CacheControlHeaderValue();
            cacheControl.NoCache = true;
            client.DefaultRequestHeaders.CacheControl = cacheControl;

            byte[] bytes = File.ReadAllBytes(csvFilePath); //c://Temp/test.csv
            HttpContent fileContent = new ByteArrayContent(bytes);
            fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("text/csv");


            try
            {

                var response = await httpClient.PostAsync(apiUrl , new MultipartFormDataContent
                        {
                            {fileContent, "\"file\"", "\"test.csv\""}
                        });
            }
            catch(Exception ex)
            {
                string message = ex.Message;
                Console.WriteLine(message); ;
            }
            finally
            {
                Console.WriteLine("Error");
            }`

or replace content.Add(fileContent, "file", "test.csv");

content.Add(fileContent, "\\"file\\"", "\\"test.csv\\");

This is for .net 4.5.

Note the \\" in the MultipartFormDataContent. There is a bug in MultipartFormDataContent.

In 4.5.1 MultipartFormDataContent wraps the data with the correct quotes.

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