本文介绍了C#中的GetResponse()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的可移植类库中有以下代码.但是它给出了
I have the following code in my portable class library. But it gives error that
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;
}
}
有人知道为什么会这样吗?
Anyone know why it is so?
推荐答案
如果要针对可移植类库进行编写,则必须将异步方法用作 GetResponse 不可用.
If you are writing for targetting the portable class library, you will have to use the asynchronous methods as GetResponse is not available.
相反,您必须使用 BeginGetReponse 和 EndGetResponse .
在您的情况下,可能看起来像这样:
In your case, this could look like this:
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,则可以这样做:
If you are using .NET 4.5, you can do it like this:
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#中的GetResponse()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!