(C#) 异步 HTTPWebRequest 无法联系服务器
我正在尝试开发 Windows Phone 7 应用程序。该应用程序的一部分包括联系 API 来检索一些数据。为此,我利用了 HTTPWebRequest 和我编写的一个小帮助器类;我调用 HTTPHelper 的 sendAPIRequest 并检索结果。
问题在于发起异步请求之后的执行链。通过调试,我发现调用了BeginGetRequestStream的回调requestCallBack。该回调随后调用 BeginGetResponse 及其回调;不幸的是,它的回调(responseCallBack)永远不会触发。我已经确定 API 所在的服务器从未被联系过(Apache 日志中没有任何内容),并且在执行 request.BeginGetResponse 后,调试器显示一个空的本地列表和一个空堆栈;回调永远不会被触发,程序也不会执行任何操作。我已经尝试了我能想到的所有类型的调试,但到这里就结束了。不会抛出任何异常,也不会出现任何异常——程序只是无法联系服务器并继续。
这是我正在使用的代码: <代码> 公共类 HTTPHelper { 公共字符串 postString { 获取;放; } 公共字符串响应数据{获取;放; }
private static ManualResetEvent readyToGo = new ManualResetEvent(false);
public void sendAPIRequest(string mode, string data)
{
GenericAPIRequest requestInformation = new GenericAPIRequest { data = data, device_id = getDeviceId(), method = mode };
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://192.168.1.69/api/master.php?source=client");
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
string postData = "device_id=" + getDeviceId() + "&data=" + JsonConvert.SerializeObject(requestInformation) + "&mode=" + mode;
postString = postData;
request.BeginGetRequestStream(new AsyncCallback(requestCallBack), request);
// Stop the thread until we've finished our HTTP request
readyToGo.WaitOne();
return;
}
private void requestCallBack(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = request.EndGetRequestStream(asynchronousResult);
byte[] postBytes = Encoding.UTF8.GetBytes(postString);
postStream.Write(postBytes, 0, postString.Length);
postStream.Close();
request.BeginGetResponse(new AsyncCallback(responseCallBack), request);
return;
}
private void responseCallBack(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
responseData = streamRead.ReadToEnd();
streamResponse.Close();
streamRead.Close();
response.Close();
// Release the thread...
readyToGo.Set();
return;
}
private string getDeviceId()
{
// Gets the unique device ID, allows us to track the device.
byte[] result = null;
object uniqueId;
if (DeviceExtendedProperties.TryGetValue("DeviceUniqueId", out uniqueId))
result = (byte[])uniqueId;
return System.BitConverter.ToString(result);
}
<代码> 关于这里做错了什么有什么建议吗?
感谢您提出的任何和所有建议。
I'm trying to develop a Windows Phone 7 application. Part of this application includes contacting an API to retrieve some data. To do so, I am utilizing HTTPWebRequest and a small helper class I've written; I call HTTPHelper's sendAPIRequest and then retrieve the result.
The problem lies in the chain of execution following the initiation of the asynchronous request. Through my debugging, I've discovered that BeginGetRequestStream's callback requestCallBack is called. This callback subsequently calls BeginGetResponse and its callback; unfortunately, its callback (responseCallBack) is never trigger. I've determined that the server the API is on is never contacted (there is nothing in Apache's logs), and after execution of request.BeginGetResponse, the debugger shows an empty list of locals and an empty stack; the callback is never triggered, and the program goes nowhere. I've tried all types of debugging I can think of, but am at an end here. No exceptions are thrown, nothing looks off--the program just simply fails to contact the server and continue.
Here's the code I'm using:
public class HTTPHelper
{
public string postString { get; set; }
public string responseData { get; set; }
private static ManualResetEvent readyToGo = new ManualResetEvent(false);
public void sendAPIRequest(string mode, string data)
{
GenericAPIRequest requestInformation = new GenericAPIRequest { data = data, device_id = getDeviceId(), method = mode };
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://192.168.1.69/api/master.php?source=client");
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
string postData = "device_id=" + getDeviceId() + "&data=" + JsonConvert.SerializeObject(requestInformation) + "&mode=" + mode;
postString = postData;
request.BeginGetRequestStream(new AsyncCallback(requestCallBack), request);
// Stop the thread until we've finished our HTTP request
readyToGo.WaitOne();
return;
}
private void requestCallBack(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = request.EndGetRequestStream(asynchronousResult);
byte[] postBytes = Encoding.UTF8.GetBytes(postString);
postStream.Write(postBytes, 0, postString.Length);
postStream.Close();
request.BeginGetResponse(new AsyncCallback(responseCallBack), request);
return;
}
private void responseCallBack(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
responseData = streamRead.ReadToEnd();
streamResponse.Close();
streamRead.Close();
response.Close();
// Release the thread...
readyToGo.Set();
return;
}
private string getDeviceId()
{
// Gets the unique device ID, allows us to track the device.
byte[] result = null;
object uniqueId;
if (DeviceExtendedProperties.TryGetValue("DeviceUniqueId", out uniqueId))
result = (byte[])uniqueId;
return System.BitConverter.ToString(result);
}
Any suggestions as to what's done wrong here?
Thanks for any and all suggestions you may have.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试拉出readyToGo.WaitOne()。这将导致线程停止并等待信号。该请求可能需要在该线程上处理,因此不会被调用。
奇怪的是,就在几分钟前,我在重置事件方面遇到了非常相似的问题,尽管它是使用 WPF 而不是 HttpRequests :)。
顺便说一句,我在 CodePlex 上有一个代码参考库,其中包含一个 HttpWebRequest 帮助程序(它可能不会直接帮助您,只是想我会提到它)。您可以随意使用它(甚至只是使用您喜欢的代码部分)。该项目名为 BizArk,该类名为 WebHelper。
Try pulling out the readyToGo.WaitOne(). That will cause the thread to stop and wait for the signal. It's likely that the request needs to process on that thread and so is not getting called.
Oddly I had a very similar problem with reset events just a few minutes ago, though it was with WPF instead of HttpRequests :).
BTW, I have a code reference library on CodePlex that includes an HttpWebRequest helper (it probably won't directly help you here, just thought I would mention it). You are free to use it anyway you want (even just to take the parts of the code you like). The project is called BizArk and the class is called WebHelper.