我有类创建用户并返回用户信息(成功)。
class POST
{
public HttpWebRequest objRequest = null;
//public static string myRequestData = string.Empty;
public String myRequestData = String.Empty;
public String urlAddress = "http://hackathon.kimhieu.info/flashcard/index.php/api/user";
public String responseString {get;set;}
public void doSend()
{
StringBuilder completeUrl = new StringBuilder(urlAddress);
objRequest = (HttpWebRequest)WebRequest.Create(urlAddress.ToString());
objRequest.ContentType ="application/x-www-form-urlencoded";
objRequest.Method = "POST";
//Adding headers
//objRequest.Headers["Header"]= "Your Value";
//objRequest.Headers["Content-Language"] = "en-US";
myRequestData = "username=abcdef&password=abcdef";
//Begins the asynchronous request
objRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback),objRequest);
}
private void GetRequestStreamCallback(IAsyncResult asyncResult)
{
HttpWebRequest objHttpWebRequest = (HttpWebRequest)asyncResult.AsyncState;
// End the operation
Stream postStream = objHttpWebRequest.EndGetRequestStream(asyncResult);
// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(myRequestData);
// Write to the request stream.
postStream.Write(byteArray, 0, myRequestData.Length);
postStream.Close();
// Start the asynchronous operation to get the response
objHttpWebRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), objHttpWebRequest);
}
private void GetResponseCallback(IAsyncResult asyncResult)
{
HttpWebRequest objHttpWebRequest = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse objHttpWebResponse = (HttpWebResponse)objHttpWebRequest.EndGetResponse(asyncResult);
Stream objStreamResponse = objHttpWebResponse .GetResponseStream();
StreamReader objStreamReader = new StreamReader(objStreamResponse );
responseString = objStreamReader.ReadToEnd(); // Got response here
myRequestData = "AAA";
//MessageBox.Show("RESPONSE :" + responseString);
// Close the stream object
objStreamResponse .Close();
objStreamReader.Close();
objHttpWebResponse.Close();
}
}
我在Main.xaml.cs中调用
POST ab = new POST();
ab.doSend();
MessageBox.Show(ab.responseString);
但它返回空字符串 我尝试在类POST POST中分配一些String,但它没有执行。 我认为GetResponseCallback(IAsyncResult asyncResult)不正确。 我该如何解决呢? 感谢提前!
答案 0 :(得分:2)
您编写了异步代码,但尝试同步读取 responseString 。只需将新事件添加到Post类:
public event Action Completed;
并从方法 GetResponseCallback 结束时运行它:
if(Completed != null)
Completed();
并以这样的方式重写您的代码:
POST ab = new POST();
ab.Completed += () => { MessageBox.Show(ab.responseString); };
ab.doSend();
应该有效