elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Recopilación Tutoriales y Manuales Hacking, Seguridad, Privacidad, Hardware, etc


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Enviar un Form usando Httprequest !!
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Enviar un Form usando Httprequest !!  (Leído 2,959 veces)
TrashAmbishion


Desconectado Desconectado

Mensajes: 756


Ver Perfil
Enviar un Form usando Httprequest !!
« en: 12 Febrero 2013, 00:55 am »

Amigos tengo un code con el que envio un FORM usando HTTPrequest con el metodo POST sin problemas, lo que sucede es que ese FORM tiene para mandar 3 fotos y ahi es donde se me traba el paraguas el CODE que tengo hasta ahora es este..

Código
  1.  
  2. Imports System
  3. Imports System.IO
  4. Imports System.Net
  5. Imports System.Text
  6.  
  7. Public Class Form1
  8.  
  9.    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
  10.  
  11.  
  12.        Dim precio As String, categoria As String, titulo As String, cuerpo As String, _
  13.        filesize As String, email As String, phone As String
  14.        'Dim boundary As String = "---------------------------" + DateTime.Now.Ticks.ToString("x")
  15.  
  16.  
  17.        ' Create the data we want to send
  18.        precio = "25"
  19.        categoria = "105"
  20.        titulo = "titulo del form"
  21.        cuerpo = "aki va el cuerpo del mensaje"
  22.        email = "user@gnome.com"
  23.        phone = "1234567"
  24.        filesize = "307200"
  25.  
  26.        ' Create a request using a URL that can receive a post.
  27.        Dim request As HttpWebRequest = HttpWebRequest.Create("URL")
  28.        ' Set the Method property of the request to POST.
  29.        request.Method = "POST"
  30.        request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
  31.  
  32.  
  33.        Dim postdata As String = "ad_price=" & precio & "&category=" & categoria & "&ad_headline=" & _
  34.            titulo & "&ad_text=" & cuerpo & "&email=" & email & "&phone=" & phone & "&MAX_FILE_SIZE=" & filesize
  35.  
  36.  
  37.        Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postdata)
  38.        ' Set the ContentType property of the WebRequest.
  39.        request.ContentType = "application/x-www-form-urlencoded"
  40.        ' Set the ContentLength property of the WebRequest.
  41.        request.ContentLength = byteArray.Length
  42.        ' Get the request stream.
  43.        Dim dataStream As Stream = request.GetRequestStream()
  44.        ' Write the data to the request stream.
  45.        dataStream.Write(byteArray, 0, byteArray.Length)
  46.        ' Close the Stream object.
  47.        dataStream.Close()
  48.        ' Get the response.
  49.        Dim response As WebResponse = request.GetResponse()
  50.        ' Display the status.
  51.        Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)
  52.        ' Get the stream containing content returned by the server.
  53.        dataStream = response.GetResponseStream()
  54.        ' Open the stream using a StreamReader for easy access.
  55.        Dim reader As New StreamReader(dataStream)
  56.        ' Read the content.
  57.        Dim responseFromServer As String = reader.ReadToEnd()
  58.        ' Display the content.
  59.        txtoutput.Text = responseFromServer
  60.        ' Clean up the streams.
  61.        reader.Close()
  62.        dataStream.Close()
  63.        response.Close()
  64.    End Sub
  65.  
  66. End Class
  67.  
  68.  

Muchas gracias por cualquier ayuda


En línea

_katze_

Desconectado Desconectado

Mensajes: 140



Ver Perfil WWW
Re: Enviar un Form usando Httprequest !!
« Respuesta #1 en: 12 Febrero 2013, 03:47 am »

busque sobre subir y descargar asincronicamente, si tengo tiempo te paso mas link pero por aqui va
http://www.c-sharpcorner.com/UploadFile/psingh/async_req11182005002032AM/async_req.aspx


En línea

TrashAmbishion


Desconectado Desconectado

Mensajes: 756


Ver Perfil
Re: Enviar un Form usando Httprequest !!
« Respuesta #2 en: 13 Febrero 2013, 19:52 pm »

Holas de nuevo chicos pues miren los avances y con ellos nuevas frustaciones, leyendo sobre como subir archivos encontre que el code anterior no se aplica hay que hacerle algunas correciones por lo que pongo mis modificaciones..

Código
  1.  
  2.    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
  3.        'UploadLocalFile()
  4.        Dim CookieJar As New CookieContainer
  5.        Dim Url As String = "http://lok.myvnc.com/insertar-anuncio.html?isDBMode=1"
  6.        Dim parametros As New NameValueCollection()
  7.  
  8.        ' Create the data we want to send
  9.        parametros.Add("var1", "1235")
  10.        parametros.Add("var2", "524")
  11.        parametros.Add("var3", "Mas información para mandar")
  12.        parametros.Add("var4", "Mas informacion para mandar")
  13.        parametros.Add("var5", "jdueybd@gjhf.com")
  14.        parametros.Add("var6", "123456")
  15.        parametros.Add("var7", "654321")
  16.        parametros.Add("var8", "Pepin")
  17.  
  18.        Uploaddata(CookieJar, Url, "C:\corazon.jpeg", "ad_picture_a", "image,jpeg", parametros)
  19.    End Sub
  20.  
  21. 'Funcion que manda la información
  22.  
  23. Public Function Uploaddata(ByVal containa As CookieContainer, ByVal uri As String, ByVal filePath As String, ByVal fileParameterName As String, ByVal contentType As String, ByVal otherParameters As Specialized.NameValueCollection) As String
  24.  
  25.        Dim boundary As String = "---------------------------" & DateTime.Now.Ticks.ToString("x")
  26.        Dim newLine As String = System.Environment.NewLine
  27.        Dim boundaryBytes As Byte() = System.Text.Encoding.ASCII.GetBytes(newLine & "--" & boundary & newLine)
  28.        Dim request As Net.HttpWebRequest = Net.WebRequest.Create(Uri)
  29.  
  30.        request.ContentType = "multipart/form-data; boundary=" & boundary
  31.        request.Method = "POST"
  32.        request.Referer = "http://lok.myvnc.com/vivienda/casa-en-la-playa/insertar-anuncio.html"
  33.        request.Headers.Add("Accept-Encoding", "gzip, deflate")
  34.        request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
  35.        request.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:16.0) Gecko/20100101 Firefox/16.0"
  36.        request.CookieContainer = containa
  37.        request.AllowAutoRedirect = True
  38.        request.Timeout = -1
  39.        request.KeepAlive = True
  40.        request.AllowWriteStreamBuffering = False
  41.  
  42.        Dim ms As New MemoryStream()
  43.        Dim formDataTemplate As String = "Content-Disposition: form-data; name=""{0}""{1}{1}{2}"
  44.  
  45.        For Each key As String In otherParameters.Keys
  46.            ms.Write(boundaryBytes, 0, boundaryBytes.Length)
  47.            Dim formItem As String = String.Format(formDataTemplate, key, newLine, otherParameters(key))
  48.            Dim formItemBytes As Byte() = System.Text.Encoding.UTF8.GetBytes(formItem)
  49.            ms.Write(formItemBytes, 0, formItemBytes.Length)
  50.        Next key
  51.  
  52.        ms.Write(boundaryBytes, 0, boundaryBytes.Length)
  53.  
  54.        Dim headerTemplate As String = "Content-Disposition: form-data; name=""{0}""; filename=""{1}""{2}Content-Type: {3}{2}{2}"
  55.        Dim header As String = String.Format(headerTemplate, fileParameterName, filePath, newLine, contentType)
  56.        Dim headerBytes As Byte() = System.Text.Encoding.UTF8.GetBytes(header)
  57.        ms.Write(headerBytes, 0, headerBytes.Length)
  58.  
  59.        Dim length As Long = ms.Length
  60.        length += New FileInfo(filePath).Length
  61.        request.ContentLength = length
  62.  
  63.        Using requestStream As IO.Stream = request.GetRequestStream()
  64.            Dim bheader() As Byte = ms.ToArray()
  65.            requestStream.Write(bheader, 0, bheader.Length)
  66.            Using fileStream As New IO.FileStream(filePath, IO.FileMode.Open, IO.FileAccess.Read)
  67.  
  68.                Dim buffer(4096) As Byte
  69.                Dim bytesRead As Int32 = fileStream.Read(buffer, 0, buffer.Length)
  70.  
  71.                Do While (bytesRead > 0)
  72.                    requestStream.Write(buffer, 0, bytesRead)
  73.                    bytesRead = fileStream.Read(buffer, 0, buffer.Length)
  74.                Loop
  75.            End Using
  76.            requestStream.Close()
  77.        End Using
  78.  
  79.        Dim response As Net.WebResponse = Nothing
  80.        Dim responseText = ""
  81.  
  82.        Try
  83.  
  84.            response = request.GetResponse()
  85.  
  86.            Using responseStream As IO.Stream = response.GetResponseStream()
  87.  
  88.                Using responseReader As New IO.StreamReader(responseStream)
  89.  
  90.                    responseText = responseReader.ReadToEnd()
  91.  
  92.                End Using
  93.  
  94.            End Using
  95.  
  96.        Catch exception As Net.WebException
  97.  
  98.            MsgBox(exception.Message)
  99.  
  100.        Finally
  101.  
  102.            response.Close()
  103.            response = Nothing
  104.            request = Nothing
  105.        End Try
  106.  
  107.        Return responseText
  108.  
  109.    End Function
  110.  
  111. End Class
  112.  
  113.  


Bueno el codigo funciona perfecto cuando abro la pagina para ver si lo que publico todo bien menos la maldita imagen que no se porque no la sube.. ahora busque un Sniffer HTTP para ver a nivel de protoclo que sucede y hay varias cosas que note esto:

Ejemplo de publicacion con el Firefox:

-----------------------------265001916915724
Content-Disposition: form-data; name="ad_picture_a"; filename="corazon.jpg"
Content-Type: image/jpeg

'Aqui va todo el archivo en codificado lenguaje maquina al server
-----------------------------265001916915724

Y otros parametros que se envian pero que el Form no me pide ningun dato de ellos, sera eso lo que esta sucediendo?.. Me parece tambien que el modo de codificacion del archivo no es el mismo que el del Mozilla lo digo porque vi ambos ejemplos y no se parecen en nada,  tambien quisiera saber si es obligatorio el orden en el que se mandan yo creo que no pero bueno... ahora algo que quiero dejar claro, el Form los datos que me exige son los que paso en el codigo quiero decir que si no pongo alguno de esos al dar click en el boton de enviar me vuelve a cargar la pagina señalandome los campos obligatorios, supongo entonces que si se publica entonces esos parametros que se envian junto con el form no son el problema en si...
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
select case sql, enviar form
PHP
alexkof158 5 5,916 Último mensaje 28 Febrero 2010, 23:34 pm
por mokoMonster
Abrir form usando una variable de cadena de caraceteres.(SOLUCIONADO)
.NET (C#, VB.NET, ASP)
ezugaru 4 8,277 Último mensaje 15 Junio 2010, 05:37 am
por raul338
enviar un form con hidden desde asp.net
Java
almita 0 3,392 Último mensaje 6 Diciembre 2010, 07:20 am
por almita
Enviar datos por POST a un FORM usando cURL
Programación C/C++
mester 4 3,916 Último mensaje 13 Septiembre 2016, 19:57 pm
por Kaxperday
Enviar form sin necesidad de Servidor? « 1 2 »
Desarrollo Web
@XSStringManolo 15 4,315 Último mensaje 14 Agosto 2019, 15:51 pm
por @XSStringManolo
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines