gpt4 book ai didi

c# - 等待 HttpWebRequest.BeginGetRequestStream 结束

转载 作者:太空宇宙 更新时间:2023-11-03 10:31:47 24 4
gpt4 key购买 nike

我正在尝试使用 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;
}

问题是我不知道如何等待方法结束。我尝试了不同的东西,例如 Task 和 Thread,但我不确定如何正确地完成它。

感谢您的帮助。

最佳答案

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com