Reputation: 525
I'm struggling to get it work but it seems doing unexpected stuff, what's wrong?
string xmlToSend = "<elementOne xmlns=\"htt..mynamespace\">.......</elementOne>";
request = (HttpWebRequest)WebRequest.Create(address);
request.Method = "POST";
request.ContentType = "text/xml; charset=utf-8";
request.Headers["Content-Length"] = xmlToSend.Length.ToString();
_postData.Append(string.Format("{0}", xmlToSend));
request.BeginGetRequestStream(new AsyncCallback(RequestReady), request);
.... }
and the BeginGetRequestString:
void RequestReady(IAsyncResult asyncResult)
{
HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest;
Debug.WriteLine("xml" + _postData.ToString());
using (Stream stream = request.EndGetRequestStream(asyncResult))
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write(_postData.ToString());
writer.Flush();
}
}
request.BeginGetResponse(new AsyncCallback(ResponseReady), request);
}
What I'm trying to achieve is setting the HTTPBODY of the request as XML, like in iOS (setHTTPBody)... is this the right way?
Upvotes: 0
Views: 1299
Reputation: 2111
You should really consider moving away from HttpWebRequest and use the new HTTPClient classes. They are much more intuitive and provides the added benefit of the new Async style architecture.
To use the new HTTPClient library in a windows 7.5 app,
Nuget the HTTP client library at https://www.nuget.org/packages/Microsoft.Net.Http (Install-Package Microsoft.Net.Http)
Nuget http://www.nuget.org/packages/Microsoft.Bcl.Async/ (Install-Package Microsoft.Bcl.Async )
Send your request
public class SendHtmlData
{
public async Task<T> SendRequest<T>(XElement xml)
{
var client = new HttpClient();
var response = await client.PostAsync("https://requestUri", CreateStringContent(xml));
var responseString = await response.RequestMessage.Content.ReadAsStringAsync();
//var responseStream = await response.RequestMessage.Content.ReadAsStreamAsync();
//var responseByte = await response.RequestMessage.Content.ReadAsByteArrayAsync();
return JsonConvert.DeserializeObject<T>(responseString);
}
private HttpContent CreateStringContent(XElement xml)
{
return new StringContent(xml.ToString(), System.Text.Encoding.UTF8, "application/xml");
}
}
In your calling UI ViewModel do something similar to
public async Task SendHtml()
{
var xml = XElement.Parse("<elementOne xmlns=\"htt..mynamespace\">.......</elementOne>");
var result = await new SendHtmlData().SendRequest<MyDataClass>(xml);
}
Upvotes: 2