我很难让它发挥作用,但似乎做了意想不到的事情,出了什么问题?
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);
.... }
和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);
}
我想要实现的是将请求的HTTPBODY设置为XML,就像在iOS中一样(setHTTPBody)......这是正确的方法吗?
答案 0 :(得分:2)
您应该考虑远离HttpWebRequest并使用新的HTTPClient类。它们更直观,并提供新的Async样式架构的额外好处。
在Windows 7.5应用程序中使用新的HTTPClient库,
在https://www.nuget.org/packages/Microsoft.Net.Http维护HTTP客户端库(Install-Package Microsoft.Net.Http)
Nuget http://www.nuget.org/packages/Microsoft.Bcl.Async/(Install-Package Microsoft.Bcl.Async)
发送您的请求
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");
}
}
在您的调用UI中,ViewModel执行与
类似的操作public async Task SendHtml()
{
var xml = XElement.Parse("<elementOne xmlns=\"htt..mynamespace\">.......</elementOne>");
var result = await new SendHtmlData().SendRequest<MyDataClass>(xml);
}