Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send XML content with HttpClient.PostAsync?

I am trying to fulfill this rest api:

public async Task<bool> AddTimetracking(Issue issue, int spentTime) {     // POST /rest/issue/{issue}/timetracking/workitem     var workItem = new WorkItem(spentTime, DateTime.Now);     var httpContent = new StringContent(workItem.XDocument.ToString());     var requestUri = string.Format("{0}{1}issue/{2}/timetracking/workitem", url, YoutrackRestUrl, issue.Id);     var respone = await httpClient.PostAsync(requestUri, httpContent);     if (!respone.IsSuccessStatusCode)     {         throw new InvalidUriException(string.Format("Invalid uri: {0}", requestUri));     }      return respone.IsSuccessStatusCode; } 

workItem.XDocument contains the following elements:

<workItem>   <date>1408566000</date>   <duration>40</duration>   <desciption>test</desciption> </workItem> 

I am getting an error from the API: Unsupported Media Type

I really have no idea how to resolve this, help is greatly appreciated. How do I marshall an XML file via a HTTP POST URI, using HttpClient?

like image 811
bas Avatar asked Aug 17 '14 18:08

bas


People also ask

How to pass XML as string to web service c#?

You use the XmlDocument class to create the initial node and then populate it with the LoadXml method. The node passes to your new web method, which takes an XmlNode instead of a string array. Listing 8-8 shows how to pass XmlDocument as an input for the InsertorderFromNode method.

How do I send an XML request?

Send XML requests with the raw data type, then set the Content-Type to text/xml . After creating a request, use the dropdown to change the request type to POST. Open the Body tab and check the data type for raw. Click Send to submit your XML Request to the specified server.


1 Answers

You might want to set the mediaType in StringContent like below:

var httpContent = new StringContent(workItem.XDocument.ToString(), Encoding.UTF8, "text/xml"); 

OR

var httpContent = new StringContent(workItem.XDocument.ToString(), Encoding.UTF8, "application/xml"); 
like image 91
ziddarth Avatar answered Sep 19 '22 15:09

ziddarth