1

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.

2
  • So the actual server expects a byte array as body instead of the actual serialized object in xml? Commented Apr 5, 2016 at 18:45
  • The web service expects an Order object. The web service does the work to take the byte array and deserialize to the model object. Commented Apr 5, 2016 at 18:56

1 Answer 1

1

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");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.