Search code examples
xamarinxamarin.androidandroidhttpclient

HttpClient posting xml serialized byte array


I have a deployed android application written in VS2010, that I'm porting over to VS2012. I'm trying to use the HttpClient to communicate with my WCF Restful webservice. The web service is an XML web service. I serialize my model objects to a byte array using XmlSerializer.

In VS2010 I successfully use WebClient like this:

using (WebClient myWebClient = new WebClient())  
{
    myWebClient.Headers.Add("Content-Type", "application/xml");
    myWebClient.UploadData(uri, postBytes);
}

However I cannot figure out how to post the same byte array using HttpClient. Here is what I have so far:

var client = new HttpClient()
client.DefaultRequestHeaders.Accept
     .Add(new MediaTypeWithQualityHeaderValue("application/xml"));

var content = new ByteArrayContent(postBytes);
Task<HttpResponseMessage> task = client.PostAsync(uri,content);
task.Wait();
HttpResponseMessage message = task.Result;

The webservice methods have these attributes:

[WebInvoke(Method="POST", RequestFormat=WebMessageFormat.Xml,
                          ResponseFormat=WebMessageFormat.Xml,
                          UriTemplate = "/Order.Xml/Process")]
[XmlSerializerFormat]

The response is nothing but 400 Bad Request. It seems that the posted content is not formatted correctly. But I don't know what to do to get it to work with the existing web service. It works correctly with WebClient.


Solution

  • You're adding "application/xml" to the 'Accept' header of the request not the 'Content-Type'.

    Please, try the following:

    content.Headers.ContentType = new MediaTypeHeaderValue("application/xml");