P K

P K

  • NA
  • 284
  • 60.8k

Cannot sent Post multipart/form-data Httpclient c# API

Dec 16 2020 10:58 PM
I am trying to send by converting string feed XML to stream multipart/form-data but getting bad request as response. Please suggest correct way to post multipart/form-data as XML or text file data
 
sample code:
  1. public async Task<string> PostAPICall(string feed,string clientID, string clientSecret)  
  2. {  
  3. try  
  4. {  
  5. HttpClient client = new HttpClient();  
  6. string uri = Constants.ApiUrl + "v3/feeds?feedType=item&setupType=byMatch";  
  7. string token = await _authentication.GetToken(clientID, clientSecret);  
  8. client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(clientID + ":" + clientSecret)));  
  9. client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  10. client.DefaultRequestHeaders.Add("WM_SEC.ACCESS_TOKEN", token );  
  11. client.DefaultRequestHeaders.Add("WM_SVC.NAME""XXXXXXXXX");  
  12. client.DefaultRequestHeaders.Add("WM_QOS.CORRELATION_ID", System.Guid.NewGuid().ToString()); //any random ID  
  13. client.DefaultRequestHeaders.Add("WM_SVC.VERSION""1.0.0");  
  14. HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uri);  
  15. MultipartFormDataContent form = new MultipartFormDataContent();  
  16. HttpContent content = new StringContent("fileToUpload");  
  17. form.Add(content, "fileToUpload");  
  18. /*convert string to stream*/  
  19. byte[] byteArray = Encoding.ASCII.GetBytes(feed);  
  20. MemoryStream stream = new MemoryStream(byteArray);  
  21. content = new StreamContent(stream);  
  22. content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")  
  23. {  
  24. Name = "feeds",  
  25. FileName = "feeds.xml"  
  26. };  
  27. form.Add(content);  
  28. string result = string.Empty;  
  29. var response = client.PostAsync(uri, form).Result;  
  30. if (response.StatusCode == System.Net.HttpStatusCode.OK)  
  31. {  
  32. result = await response.Content.ReadAsStringAsync();  
  33. }  
  34. return result;  
  35. }  
  36. catch (Exception e)  
  37. {  
  38. throw e;  
  39. }  
  40. }

Answers (1)