Windows Phone 7 응용 프로그램을 개발하려고합니다. 이 응용 프로그램의 일부에는 일부 데이터를 검색하기 위해 API에 연결하는 것이 포함됩니다. 이렇게하려면 HTTPWebRequest와 내가 작성한 작은 도우미 클래스를 사용하고 있습니다. HTTPHelper의 sendAPIRequest를 호출 한 다음 결과를 검색합니다.(C#) 비동기 HTTPWebRequest 서버에 연결하지 못했습니다.
문제는 비동기 요청을 시작한 후 실행 체인에 있습니다. 디버깅을 통해 BeginGetRequestStream의 콜백 requestCallBack이 호출되었음을 알았습니다. 이 콜백은 이후에 BeginGetResponse와 콜백을 호출합니다. 불행하게도 콜백 (responseCallBack)은 결코 트리거되지 않습니다. API가있는 서버가 절대로 접속되지 않았으며 (Apache의 로그에는 아무 것도 없음) request.BeginGetResponse를 실행 한 후 디버거가 지역 목록과 빈 스택을 표시한다는 것을 알았습니다. 콜백은 결코 트리거되지 않으며 프로그램은 아무데도 가지 않습니다. 내가 생각할 수있는 모든 종류의 디버깅을 시도했지만 여기서 끝이다. 예외는 발생하지 않으며 외면되지 않습니다. 프로그램은 단순히 서버에 접속하여 계속 실패합니다.
다음 코드는 내가 사용하고있는 코드입니다. 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);
}
여기에 잘못된 것이 있습니까?
당신이 가진 모든 제안에 감사드립니다.
그걸 한 것처럼 보입니다. MainPage.xaml.cs에 ResponseData를 자유롭게 검색 할 수 있음 (즉, 비동기 요청이 완료 되었음)을 알릴 수있는 방법에 대한 제안 사항이 있습니까? 나는 응답이 수신 될 때까지 스레드를 멈출 수 있기를 바랬지 만 그것은 명백한 실행 가능한 해결책이 아닙니다. – roswell
그것은 실제로 당신이 성취하고자하는 것에 달려 있습니다. 아마도 당신은 responseCallback 메소드로부터 메소드를 호출 할 수있을 것이다. 해당 메소드가 처리하는 대상에 대해 다소 벙어리해야하는 경우 대리자를 전송하고 완료되면이를 호출 할 수 있습니다. – Brian