我正在尝试使用 HttpWebRequest.BeginGetRequestStream
方法。在我的方法中,我得到了一些 Json
。我需要等待这个方法 (HttpWebRequest.BeginGetRequestStream)
结束来分析我的 Json。
这是我的代码:
private string API_Query(string url)
{
HttpWebRequest requete = (HttpWebRequest)HttpWebRequest.Create(url);
requete.Method = "POST";
requete.ContentType = "application/x-www-form-urlencoded";
requete.BeginGetRequestStream(DebutReponse, requete);//wait the end of this method
//analyse the json here
return null;
}
问题是我不知道如何等待方法结束。我尝试了不同的方法,例如任务和线程,但我不确定如何正确执行。
感谢您的帮助。
最佳答案
The problem is that I don't know how to wait the end the method.
有很多方法可以做到这一点。在我看来,您想同步调用请求,我建议只需调用 GetResponseStream
:
private string ApiQuery(string url)
{
HttpWebRequest requete = (HttpWebRequest)HttpWebRequest.Create(url);
requete.Method = "POST";
requete.ContentType = "application/x-www-form-urlencoded";
using (var requestStream = requete.GetRequestStream())
{
// Write to request stream
}
using (var responseStream = requete.GetResponse())
{
// Read the respone stream, parsing out your JSON.
}
}
编辑:
正如您在评论中提到的,这是一个 Silverlight 项目。这意味着您没有 HttpWebRequest
的同步版本。相反,您可以使用 WebClient
:
var webClient = new WebClient()
webClient.OpenReadCompleted += OnUploadCompleted;
webClient.OpenReadAsync(url, data);
private void OnUploadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error != null)
{
// Error, do something useful
return;
}
using (var responseStream = e.Result)
{
byte[] data = (byte[]) e.UserState;
// Read response from stream.
}
}
关于c# - 等待 HttpWebRequest.BeginGetRequestStream 结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29863606/