我正在开发一个 Metro 应用程序,在该应用程序中,我在后台服务中发送 Web 请求,但没有获得 Web 响应。我这样编码:
private void SendRequest(string url, Action OnResponse, string requestParameter)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url));
request.Method = "POST";
request.ContentType = "text/xml";
request.BeginGetRequestStream(delegate(IAsyncResult req)
{
var outStream = request.EndGetRequestStream(req);
using (StreamWriter w = new StreamWriter(outStream))
w.Write(requestParameter);
request.BeginGetResponse(delegate(IAsyncResult result)
{
try
{
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
using (var stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream))
{
string response1 = reader.ReadToEnd();
OnResponse(response1);
}
}
}
catch (Exception ex)
{
}
}, null);
}, null);
}
我也试过这样
HttpClient client = new HttpClient();
HttpContent content = new StringContent(requestParameter);
conent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/xml");
HttpResponseMessage response = await client.PostAsync(url, content);
有什么原因我没有得到回应或任何其他方法来做到这一点。我在正常执行中执行了相同的代码,并且运行良好,但在后台服务中却没有。