我正在开发一个移动应用程序,从中我将包含用于用户身份验证的 XML 的 HTTP POST 请求发送到基于 PHP 的 Web 服务。
在方法中接收来自 Web 服务的响应GetResponseCallback(IAsyncResult asynchronousResult)
。
请参阅下面给出的代码的某些部分以发送请求。
class XMLHttpRequestHandler
{
private HttpWebRequest vWebRequestObj;
private string vXMLString;
private string vResponse;
public void SendXMLHttpRequest(string pXMLString)
{
vWebRequestObj = (HttpWebRequest)HttpWebRequest.CreateHttp("https://test.mydomain.com/mywebservice.php");
vWebRequestObj.Method = "PUT";
vWebRequestObj.ContentType = "text/xml; charset=utf-8";
// initialize the XML string
vXMLString = pXMLString;
// Convert the string into a byte array and calculate the length.
vWebRequestObj.ContentLength = Encoding.UTF8.GetBytes(vXMLString).Length;
// start the asynchronous operation
vWebRequestObj.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), vWebRequestObj);
}
private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
// create the WebRequestObject
HttpWebRequest vWebRequestObj = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation and get the stream for writing the XML.
Stream postStream = vWebRequestObj.EndGetRequestStream(asynchronousResult);
// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(vXMLString);
// Write to the request stream.
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the asynchronous operation to get the response
vWebRequestObj.BeginGetResponse(new AsyncCallback(GetResponseCallback), vWebRequestObj);
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
// create the WebRequestObject
HttpWebRequest vWebRequestObj = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
HttpWebResponse vWebResponseObj = (HttpWebResponse)vWebRequestObj.EndGetResponse(asynchronousResult);
// get the response stream
Stream ResponseStream = vWebResponseObj.GetResponseStream();
// create the stream reader object
StreamReader ResponseStreamReader = new StreamReader(ResponseStream);
// read the stream
vResponse = ResponseStreamReader.ReadToEnd();
// output the stream
System.Diagnostics.Debug.WriteLine(vResponse);
// Close the stream object
ResponseStream.Close();
ResponseStreamReader.Close();
// Release the HttpWebResponse
vWebResponseObj.Close();
}
}
我正在SendXMLHttpRequest(string pXMLString)
像这样从我的项目中的其他类调用该方法
string XMLString = "<testxml><username>abcd</username><password>xyz</password></testxml>";
// send the XML HTTP request
XMLHttpRequestHandler ob = new XMLHttpRequestHandler();
string webserviceresponse = ob.SendXMLHttpRequest(XMLString);
我面临的问题是我无法弄清楚如何webserviceresponse
在调用代码的变量中接收响应字符串。我该如何解决这个问题?