gpt4 book ai didi

c# - C# 中的 GetResponse()

转载 作者:太空狗 更新时间:2023-10-30 00:24:55 26 4
gpt4 key购买 nike

我的可移植类库中有以下代码。但它给出了错误

System.Net.HttpWebRequest does not contain a definition for GetResponse().

public async Task<object> GetStateByUserId(string userID)
{
HttpWebRequest request;
Stream receiveStream;
StreamReader readStream;

request =(HttpWebRequest)CreateGetWebRequest("state/uid/"+userID);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {

receiveStream = response.GetResponseStream ();
readStream = new StreamReader(receiveStream);
string str = readStream.ReadToEnd().ToString();
s = JsonConvert.DeserializeObject<state>(str);
return s;
}


}

谁知道为什么会这样?

最佳答案

如果您编写的目标是可移植类库,则必须使用异步方法 GetResponse不可用。

相反,您必须使用 BeginGetReponseEndGetResponse .

在您的情况下,这可能看起来像这样:

public void StartRequest ()
{
HttpWebRequest request = (HttpWebRequest)CreateGetWebRequest("state/uid/"+userID);
request.BeginGetResponse(new AsyncCallback(FinishRequest), request);
}

private void FinishRequest (IAsyncResult result)
{
HttpWebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result) as HttpWebResponse;

Stream receiveStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(receiveStream);

// ...
}

如果您使用的是 .NET 4.5,您可以这样做:

HttpWebRequest request = (HttpWebRequest)CreateGetWebRequest("state/uid/"+userID);
Task<HttpWebResponse> requestTask = Task.Factory.FromAsync<HttpWebResponse>(request.BeginGetResponse, request.EndGetResponse, request);
using (var response = await requestTask)
{
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(receiveStream);
}

关于c# - C# 中的 GetResponse(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20609528/

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