我有一段代码可以使用HttpWeb请求 and HttpWeb响应但我想将其转换为使用Http客户端 and Http响应消息.
这是有效的代码块......
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 未正确附加(也许)。
The HttpClient.Post
方法有一个重载,需要一个contentType
参数,试试这个:
// Make the request and retrieve the response
response = client.Post(serviceReq, "text/xml", content);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)