我有类来创建用户并返回用户信息(成功)。
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 myData 类中分配一些字符串,但它没有执行。我认为 GetResponseCallback(IAsyncResult asyncResult) 不正确。我该如何解决。感谢提前!