2011-05-10 13 views
6

tengo un trozo de código que funciona usando la HttpWebRequest y HttpWebResponse pero me gustaría convertirlo a utilizar HttpClient y HttpResponseMessage.HttpWebRequest Vs HttpClient

Este es el trozo de código que funciona ...

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(); 

Y este es el código que me gustaría reemplazarlo con, si tan sólo pudiera conseguir que funcione.

/// <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; 
} 

Creo que el problema está creando el objeto de contenido y el XML no se está conectado correctamente (tal vez).

+0

¿Qué exactamente no funciona? ¿No compila? ¿O tienes errores de tiempo de ejecución? ¿Qué errores? – fretje

+0

¿Cuál es el error? – Aliostad

+0

La solicitud se envía, pero el servicio que maneja la solicitud entrante piensa que no hay datos y, por lo tanto, devuelve "Acceso no autorizado", que es la respuesta predeterminada para ese servicio. – TeamWild

Respuesta

1

Me gustaría saber la razón por la que el enfoque no funciona y el otro hace, pero acabo de Don No tengo tiempo para cavar más. {: O (

De todos modos, esto es lo que encontré

Un fallo se produce cuando se crea el contenido de la solicitud utilizando la siguiente

HttpContent content = HttpContentExtensions.Create(root, Encoding.UTF8, "text/xml"); 

pero funciona correctamente cuando se crea el contenido similares. esto ...

HttpContent content = HttpContent.Create(root.ToString(), Encoding.UTF8, "text/xml"); 

La función de trabajo final es la siguiente:

/// <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; 

      #if DEBUG 
      // Force the request to use fiddler 
      client.TransportSettings.Proxy = new WebProxy("127.0.0.1", 8888); 
      #endif 

      // Create a content object for the request 
      HttpContent content = HttpContent.Create(root.ToString(), Encoding.UTF8, "text/xml"); 

      // 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 user credentials", ex); 
     valid = false; 
     m_uid = string.Empty; 
    } 

    return valid; 
} 

Gracias.

1

HttpClient.Post El método tiene una sobrecarga que toma un parámetro contentType, intente esto:

// Make the request and retrieve the response 
response = client.Post(serviceReq, "text/xml", content); 
+0

Gracias. Como puede ver a continuación, yo estaba en el mismo proceso de pensamiento. El problema que tengo parece estar relacionado con la forma en que se crea el objeto de contenido en lugar del método de publicación utilizado. – TeamWild