¿Que puedo estar pasando por alto?, saludos y gracias.
1. ¿Te has asegurado de codificar los valores de los parámetros en caso de que contengan caracteres especiales como espacios en blanco, puntos, etc?:
Código
HttpUtility.UrlEncode(usuario); HttpUtility.UrlEncode(contraseña);
2. ¿Has comprobado que le estás pasando las cabeceras correctas?.
3. De todas formas podrías necesitar más que eso, prueba a obtener la Cookie de visitante en la página principal, y luego a loguearte usando dicha cookie,
escribí este snippet al que se le puede dar un uso más o menos genérico que podría servir para tu situación, le hice unas pequeñas modificaciones para adaptarlo a tus necesidades, solo modifica los valores de la propiedades 'UrlMain', 'UrlLogin', 'UrlLoginQueryFormat', comprueba las cabeceras que asigno en 'RequestHeadersPostLogin' sean correctas y no falten más, y por último llama al método 'CheckLogin' para evaluar el login.
VB.Net:
Código
''' <summary> ''' Gets the main url. ''' </summary> ''' <value>The main url.</value> Public ReadOnly Property UrlMain As String Get Return "http://www.cgwallpapers.com/" End Get End Property ''' <summary> ''' Gets the login url. ''' </summary> ''' <value>The login url.</value> Public ReadOnly Property UrlLogin As String Get Return "http://www.cgwallpapers.com/login.php" End Get End Property ''' <summary> ''' Gets the login query string format. ''' </summary> ''' <value>The login query string format.</value> Public ReadOnly Property UrlLoginQueryFormat As String Get Return "usuario={0}&contrasena={1}" End Get End Property ''' <summary> ''' Gets the headers for a Login POST request. ''' </summary> ''' <value>The headers for a Login POST request.</value> Public ReadOnly Property RequestHeadersPostLogin As WebHeaderCollection Get Dim headers As New WebHeaderCollection With headers .Add("Accept-Language", "en-us,en;q=0.5") .Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7") .Add("Keep-Alive", "99999") End With Return headers End Get End Property ''' <summary> ''' Determines whether the user is logged in the site. ''' </summary> Private isLogged As Boolean ''' <summary> ''' Gets the cookie container. ''' </summary> ''' <value>The cookie container.</value> Public ReadOnly Property CookieCollection As CookieCollection Get Return Me.cookieCollection1 End Get End Property ''' <summary> ''' The cookie container. ''' </summary> Private cookieCollection1 As CookieCollection ''' <summary> ''' Defines the query data for a LoginPost request. ''' </summary> Private NotInheritable Class LoginQueryData ''' <summary> ''' Gets the Usuario field. ''' </summary> ''' <value>The Usuario field.</value> Public Property Usuario As String ''' <summary> ''' Gets or sets the Conteasena field. ''' </summary> ''' <value>The Conteasena field.</value> Public Property Contrasena As String End Class ''' <summary> ''' Gets a formatted <see cref="String"/> representation of a <see cref="LoginQueryData"/> object. ''' </summary> ''' <param name="loginQueryData">The <see cref="LoginQueryData"/> object that contains the login query fields.</param> ''' <returns>A formatted <see cref="String"/> representation of a <see cref="LoginQueryData"/> object.</returns> Private Function GetLoginQueryString(ByVal loginQueryData As LoginQueryData) As String Return String.Format(Me.UrlLoginQueryFormat, loginQueryData.Usuario, loginQueryData.Contrasena) End Function ''' <summary> ''' Sets the cookie container. ''' </summary> ''' <param name="url">The url.</param> ''' <param name="cookieCollection">The cookie collection.</param> ''' <returns>CookieContainer.</returns> Private Function SetCookieContainer(ByVal url As String, ByVal cookieCollection As CookieCollection) As CookieContainer Dim cookieContainer As New CookieContainer Dim refDate As Date For Each oldCookie As Cookie In cookieCollection If Not DateTime.TryParse(oldCookie.Value, refDate) Then Dim newCookie As New Cookie With newCookie .Name = oldCookie.Name .Value = oldCookie.Value .Domain = New Uri(url).Host .Secure = False End With cookieContainer.Add(newCookie) End If Next oldCookie Return cookieContainer End Function ''' <summary> ''' Converts cookie string to global cookie collection object. ''' </summary> ''' <param name="cookie">The cookie string.</param> ''' <param name="cookieCollection">The cookie collection.</param> Private Sub SaveCookies(ByVal cookie As String, ByRef cookieCollection As CookieCollection) Dim cookieStrings() As String = cookie.Trim. Replace("path=/,", String.Empty). Replace("path=/", String.Empty). Split({";"c}, StringSplitOptions.RemoveEmptyEntries) cookieCollection = New CookieCollection For Each cookieString As String In cookieStrings If Not String.IsNullOrEmpty(cookieString.Trim) Then cookieCollection.Add(New Cookie(name:=cookieString.Trim.Split("="c)(0), value:=cookieString.Trim.Split("="c)(1))) End If Next cookieString End Sub ''' <summary> ''' Convert cookie container object to global cookie collection object. ''' </summary> ''' <param name="cookieContainer">The cookie container.</param> ''' <param name="cookieCollection">The cookie collection.</param> ''' <param name="url">The url.</param> Private Sub SaveCookies(ByVal cookieContainer As CookieContainer, ByRef cookieCollection As CookieCollection, ByVal url As String) cookieCollection = New CookieCollection For Each cookie As Cookie In cookieContainer.GetCookies(New Uri(url)) cookieCollection.Add(cookie) Next cookie End Sub ''' <param name="url">The url.</param> ''' <param name="cookieCollection">The cookie collection.</param> ''' <returns><c>true</c> if successfull, <c>false</c> otherwise.</returns> Private Function GetMethod(ByVal url As String, ByRef cookieCollection As CookieCollection) As Boolean Dim request As HttpWebRequest = Nothing Dim response As HttpWebResponse = Nothing Dim sr As StreamReader = Nothing Dim result As Boolean = False Try Debug.WriteLine(String.Format("Headers: {0}", String.Join(Environment.NewLine, Me.RequestHeadersPostLogin))) request = DirectCast(HttpWebRequest.Create(url), HttpWebRequest) With request .Method = "GET" .Headers = Me.RequestHeadersPostLogin .Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5" .UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0" .AllowAutoRedirect = False .KeepAlive = True End With ' Get the server response. response = DirectCast(request.GetResponse, HttpWebResponse) If request.HaveResponse Then ' Save the cookie info. Me.SaveCookies(response.Headers("Set-Cookie"), cookieCollection) ' Get the server response. response = DirectCast(request.GetResponse, HttpWebResponse) sr = New StreamReader(response.GetResponseStream) Using sr ' Read the response from the server, but we do not save it. sr.ReadToEnd() End Using result = True Else ' No response received from server. Throw New Exception(String.Format("No response received from server with url: {0}", url)) result = False End If Catch ex As Exception Throw result = False Finally If sr IsNot Nothing Then sr.Dispose() End If If response IsNot Nothing Then response.Close() End If End Try Return result End Function ''' <param name="loginData">The login post data.</param> ''' <param name="cookieCollection">The cookie collection.</param> ''' <returns><c>true</c> if successfull, <c>false</c> otherwise.</returns> Private Function PostLoginMethod(ByVal loginData As LoginQueryData, ByRef cookieCollection As CookieCollection) As Boolean Dim request As HttpWebRequest = Nothing Dim response As HttpWebResponse = Nothing Dim sw As StreamWriter = Nothing Dim initialCookieCount As Integer = 0 Dim postData As String Dim result As Boolean = False Try Debug.WriteLine(String.Format("Accept: {0}", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")) Debug.WriteLine(String.Format("Headers: {0}", String.Join(Environment.NewLine, Me.RequestHeadersPostLogin))) request = DirectCast(HttpWebRequest.Create(Me.UrlLogin), HttpWebRequest) With request .Method = "POST" .Headers = Me.RequestHeadersPostLogin .Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" .ContentType = "application/x-www-form-urlencoded" .UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0" .Referer = Me.UrlMain End With If cookieCollection IsNot Nothing Then ' Pass cookie info from the login page. request.CookieContainer = Me.SetCookieContainer(Me.UrlLogin, cookieCollection) End If ' Set the post data. postData = Me.GetLoginQueryString(loginData) sw = New StreamWriter(request.GetRequestStream) Using sw sw.Write(postData) ' Post the data to the server. End Using ' Get the server response. initialCookieCount = request.CookieContainer.Count response = DirectCast(request.GetResponse, HttpWebResponse) If request.CookieContainer.Count > initialCookieCount Then ' Login successful. result = True Else ' Login unsuccessful. result = False End If If(result, "Successful (True)", "Unsuccessful (False)"))) If result Then ' Save new login cookies. Me.SaveCookies(request.CookieContainer, cookieCollection, Me.UrlMain) End If Catch ex As Exception Throw Finally If sw IsNot Nothing Then sw.Dispose() End If If response IsNot Nothing Then response.Close() End If End Try Me.isLogged = result Return result End Function ''' <summary> ''' Determines whether the account can log in CGWallpapers site. ''' </summary> ''' <returns><c>true</c> if the account can log in CGWallpapers site, <c>false</c> otherwise.</returns> Public Function CheckLogin(ByVal username As String, ByVal password As String) As Boolean If Me.GetMethod(Me.UrlMain, Me.cookieCollection1) Then Dim loginQueryData As New LoginQueryData With { .Usuario = HttpUtility.UrlEncode(username), .Contrasena = HttpUtility.UrlEncode(password) } Return Me.PostLoginMethod(loginQueryData, Me.cookieCollection1) Else Return False End If ' Me.GetMethod End Function
Traducción online a C# (sin testear):
Código
/// <summary> /// Gets the main url. /// </summary> /// <value>The main url.</value> public string UrlMain { get { return "http://www.cgwallpapers.com/"; } } /// <summary> /// Gets the login url. /// </summary> /// <value>The login url.</value> public string UrlLogin { get { return "http://www.cgwallpapers.com/login.php"; } } /// <summary> /// Gets the login query string format. /// </summary> /// <value>The login query string format.</value> public string UrlLoginQueryFormat { get { return "usuario={0}&contrasena={1}"; } } /// <summary> /// Gets the headers for a Login POST request. /// </summary> /// <value>The headers for a Login POST request.</value> public WebHeaderCollection RequestHeadersPostLogin { get { var _with1 = headers; _with1.Add("Accept-Language", "en-us,en;q=0.5"); _with1.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); _with1.Add("Keep-Alive", "99999"); return headers; } } /// <summary> /// Determines whether the user is logged in the site. /// </summary> private bool isLogged; /// <summary> /// Gets the cookie container. /// </summary> /// <value>The cookie container.</value> public CookieCollection CookieCollection { get { return this.cookieCollection1; } } /// <summary> /// The cookie container. /// </summary> private CookieCollection cookieCollection1; /// <summary> /// Defines the query data for a LoginPost request. /// </summary> private sealed class LoginQueryData { /// <summary> /// Gets the Usuario field. /// </summary> /// <value>The Usuario field.</value> public string Usuario { get; set; } /// <summary> /// Gets or sets the Conteasena field. /// </summary> /// <value>The Conteasena field.</value> public string Contrasena { get; set; } } /// <summary> /// Gets a formatted <see cref="String"/> representation of a <see cref="LoginQueryData"/> object. /// </summary> /// <param name="loginQueryData">The <see cref="LoginQueryData"/> object that contains the login query fields.</param> /// <returns>A formatted <see cref="String"/> representation of a <see cref="LoginQueryData"/> object.</returns> private string GetLoginQueryString(LoginQueryData loginQueryData) { return string.Format(this.UrlLoginQueryFormat, loginQueryData.Usuario, loginQueryData.Contrasena); } /// <summary> /// Sets the cookie container. /// </summary> /// <param name="url">The url.</param> /// <param name="cookieCollection">The cookie collection.</param> /// <returns>CookieContainer.</returns> private CookieContainer SetCookieContainer(string url, CookieCollection cookieCollection) { System.DateTime refDate = default(System.DateTime); foreach (Cookie oldCookie in cookieCollection) { if (!DateTime.TryParse(oldCookie.Value, refDate)) { var _with2 = newCookie; _with2.Name = oldCookie.Name; _with2.Value = oldCookie.Value; _with2.Secure = false; cookieContainer.Add(newCookie); } } return cookieContainer; } /// <summary> /// Converts cookie string to global cookie collection object. /// </summary> /// <param name="cookie">The cookie string.</param> /// <param name="cookieCollection">The cookie collection.</param> private void SaveCookies(string cookie, ref CookieCollection cookieCollection) { string[] cookieStrings = cookie.Trim.Replace("path=/,", string.Empty).Replace("path=/", string.Empty).Split({ ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string cookieString in cookieStrings) { if (!string.IsNullOrEmpty(cookieString.Trim)) { cookieCollection.Add(new Cookie(name: cookieString.Trim.Split('=')(0), value: cookieString.Trim.Split('=')(1))); } } } /// <summary> /// Convert cookie container object to global cookie collection object. /// </summary> /// <param name="cookieContainer">The cookie container.</param> /// <param name="cookieCollection">The cookie collection.</param> /// <param name="url">The url.</param> private void SaveCookies(CookieContainer cookieContainer, ref CookieCollection cookieCollection, string url) { cookieCollection.Add(cookie); } } /// <param name="url">The url.</param> /// <param name="cookieCollection">The cookie collection.</param> /// <returns><c>true</c> if successfull, <c>false</c> otherwise.</returns> private bool GetMethod(string url, ref CookieCollection cookieCollection) { Debug.WriteLine("[+] GetMethod function started."); HttpWebRequest request = null; HttpWebResponse response = null; StreamReader sr = null; bool result = false; try { Debug.WriteLine("[+] Attempting to perform a request with:"); Debug.WriteLine(string.Format("Method: {0}", "GET")); Debug.WriteLine(string.Format("Headers: {0}", string.Join(Environment.NewLine, this.RequestHeadersPostLogin))); request = (HttpWebRequest)HttpWebRequest.Create(url); var _with3 = request; _with3.Method = "GET"; _with3.Headers = this.RequestHeadersPostLogin; _with3.Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"; _with3.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0"; _with3.AllowAutoRedirect = false; _with3.KeepAlive = true; Debug.WriteLine("[-] Request done."); // Get the server response. Debug.WriteLine("[+] Getting server response..."); response = (HttpWebResponse)request.GetResponse; Debug.WriteLine("[-] Getting server response done."); if (request.HaveResponse) { // Save the cookie info. Debug.WriteLine("[+] Saving cookies..."); this.SaveCookies(response.Headers("Set-Cookie"), ref cookieCollection); Debug.WriteLine("[-] Saving cookies done."); // Get the server response. Debug.WriteLine("[+] Getting server response..."); response = (HttpWebResponse)request.GetResponse; Debug.WriteLine("[-] Getting server response done."); Debug.WriteLine("[+] Reading server response..."); using (sr) { // Read the response from the server, but we do not save it. sr.ReadToEnd(); } result = true; Debug.WriteLine("[-] Reading server response done."); // No response received from server. } else { result = false; } } catch (Exception ex) { throw; result = false; } finally { if (sr != null) { sr.Dispose(); } if (response != null) { response.Close(); } } Debug.WriteLine("[-] GetMethod function finished."); Debug.WriteLine("[i] Returning result value..."); return result; } /// <param name="loginData">The login post data.</param> /// <param name="cookieCollection">The cookie collection.</param> /// <returns><c>true</c> if successfull, <c>false</c> otherwise.</returns> private bool PostLoginMethod(LoginQueryData loginData, ref CookieCollection cookieCollection) { Debug.WriteLine("[+] PostLoginMethod function started."); HttpWebRequest request = null; HttpWebResponse response = null; StreamWriter sw = null; int initialCookieCount = 0; string postData = null; bool result = false; try { Debug.WriteLine("[+] Attempting to perform a login request with:"); Debug.WriteLine(string.Format("Method: {0}", "POST")); Debug.WriteLine(string.Format("Referer: {0}", this.UrlMain)); Debug.WriteLine(string.Format("Accept: {0}", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")); Debug.WriteLine(string.Format("ContentType: {0}", "application/x-www-form-urlencoded")); Debug.WriteLine(string.Format("Headers: {0}", string.Join(Environment.NewLine, this.RequestHeadersPostLogin))); request = (HttpWebRequest)HttpWebRequest.Create(this.UrlLogin); var _with4 = request; _with4.Method = "POST"; _with4.Headers = this.RequestHeadersPostLogin; _with4.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; _with4.ContentType = "application/x-www-form-urlencoded"; _with4.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0"; _with4.Referer = this.UrlMain; Debug.WriteLine("[-] Request done."); Debug.WriteLine("[+] Passing request cookie info..."); // Pass cookie info from the login page. if (cookieCollection != null) { request.CookieContainer = this.SetCookieContainer(this.UrlLogin, cookieCollection); } Debug.WriteLine("[-] Passing request cookie info done."); // Set the post data. Debug.WriteLine("[+] Setting post data with:"); Debug.WriteLine(string.Format("Usuario: {0}", loginData.Usuario)); Debug.WriteLine(string.Format("Contrasena: {0}", loginData.Contrasena)); postData = this.GetLoginQueryString(loginData); using (sw) { sw.Write(postData); // Post the data to the server. } Debug.WriteLine("[-] Setting post data done."); // Get the server response. Debug.WriteLine("[+] Getting server response..."); initialCookieCount = request.CookieContainer.Count; response = (HttpWebResponse)request.GetResponse; Debug.WriteLine("[-] Getting server response done."); // Login successful. if (request.CookieContainer.Count > initialCookieCount) { result = true; // Login unsuccessful. } else { result = false; } Debug.WriteLine(string.Format("[i] Login response result is: {0}", result ? "Successful (True)" : "Unsuccessful (False)")); // Save new login cookies. if (result) { Debug.WriteLine("[+] Saving new login cookies..."); this.SaveCookies(request.CookieContainer, ref cookieCollection, this.UrlMain); Debug.WriteLine("[-] Saving new login cookies done."); } } catch (Exception ex) { throw; } finally { if (sw != null) { sw.Dispose(); } if (response != null) { response.Close(); } } Debug.WriteLine("[-] PostLoginMethod function finished."); Debug.WriteLine("[i] Returning result value..."); this.isLogged = result; return result; } /// <summary> /// Determines whether the account can log in CGWallpapers site. /// </summary> /// <returns><c>true</c> if the account can log in CGWallpapers site, <c>false</c> otherwise.</returns> public bool CheckLogin(string username, string password) { if (this.GetMethod(this.UrlMain, this.cookieCollection1)) { Usuario = HttpUtility.UrlEncode(username), Contrasena = HttpUtility.UrlEncode(password) }; return this.PostLoginMethod(loginQueryData, this.cookieCollection1); } else { return false; } // Me.GetMethod } //======================================================= //Service provided by Telerik (www.telerik.com) //=======================================================