我有一段代碼,即作品使用的HttpWebRequest和HttpWebResponse但我想將其轉換爲使用的HttpClient和HttpResponseMessage。的HttpWebRequest Vs的HttpClient的
這是該工程的代碼塊...
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(serviceReq);
request.Method = "POST";
request.ContentType = "text/xml";
string xml = @"<?xml version=""1.0""?><root><login><user>flibble</user>" +
@"<pwd></pwd></login></root>";
request.ContentLength = xml.Length;
using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream()))
{
dataStream.Write(xml);
dataStream.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
這就是我想和來取代它,如果我能得到它的工作的代碼。
/// <summary>
/// Validate the user credentials held as member variables
/// </summary>
/// <returns>True if the user credentials are valid, else false</returns>
public bool ValidateUser()
{
bool valid = false;
try
{
// Create the XML to be passed as the request
XElement root = BuildRequestXML("LOGON");
// Add the action to the service address
Uri serviceReq = new Uri(m_ServiceAddress + "?obj=LOGON");
// Create the client for the request to be sent from
using (HttpClient client = new HttpClient())
{
// Initalise a response object
HttpResponseMessage response = null;
// Create a content object for the request
HttpContent content = HttpContentExtensions.
CreateDataContract<XElement>(root);
// Make the request and retrieve the response
response = client.Post(serviceReq, content);
// Throw an exception if the response is not a 200 level response
response.EnsureStatusIsSuccessful();
// Retrieve the content of the response for processing
response.Content.LoadIntoBuffer();
// TODO: parse the response string for the required data
XElement retElement = response.Content.ReadAsXElement();
}
}
catch (Exception ex)
{
Log.WriteLine(Category.Serious,
"Unable to validate the Credentials", ex);
valid = false;
m_uid = string.Empty;
}
return valid;
}
我認爲這個問題是創建內容對象和XML沒有被正確連接(也許)。
究竟什麼不行?不編譯?或者你有運行時錯誤?哪些錯誤? – fretje 2011-05-10 15:35:45
什麼是錯誤? – Aliostad 2011-05-10 15:36:07
發送請求,但處理入站請求的服務認爲沒有數據,因此會返回「未經授權的訪問」,這是該服務的默認響應。 – TeamWild 2011-05-10 15:38:39