0

我正在努力让它工作,但它似乎做了意想不到的事情,怎么了?

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) 中一样……这是正确的方法吗?

4

1 回答 1

2

您真的应该考虑放弃 HttpWebRequest 并使用新的 HTTPClient 类。它们更加直观,并提供了新的异步风格架构的额外好处。

要在 Windows 7.5 应用程序中使用新的 HTTPClient 库,

在https://www.nuget.org/packages/Microsoft.Net.Http (Install-Package Microsoft.Net.Http) Nuget HTTP 客户端库

Nuget http://www.nuget.org/packages/Microsoft.Bcl.Async/(安装包 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);
}
于 2013-08-27T10:44:32.980 回答