Enviar un Form usando Httprequest !!

(1/1)

TrashAmbishion:
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
 
Imports System
Imports System.IO
Imports System.Net
Imports System.Text
 
Public Class Form1
 
   Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
 
 
       Dim precio As String, categoria As String, titulo As String, cuerpo As String, _
       filesize As String, email As String, phone As String
       'Dim boundary As String = "---------------------------" + DateTime.Now.Ticks.ToString("x")
 
 
       ' Create the data we want to send
       precio = "25"
       categoria = "105"
       titulo = "titulo del form"
       cuerpo = "aki va el cuerpo del mensaje"
       email = "user@gnome.com"
       phone = "1234567"
       filesize = "307200"
 
       ' Create a request using a URL that can receive a post.
       Dim request As HttpWebRequest = HttpWebRequest.Create("URL")
       ' Set the Method property of the request to POST.
       request.Method = "POST"
       request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
 
 
       Dim postdata As String = "ad_price=" & precio & "&category=" & categoria & "&ad_headline=" & _
           titulo & "&ad_text=" & cuerpo & "&email=" & email & "&phone=" & phone & "&MAX_FILE_SIZE=" & filesize
 
 
       Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postdata)
       ' Set the ContentType property of the WebRequest.
       request.ContentType = "application/x-www-form-urlencoded"
       ' Set the ContentLength property of the WebRequest.
       request.ContentLength = byteArray.Length
       ' Get the request stream.
       Dim dataStream As Stream = request.GetRequestStream()
       ' Write the data to the request stream.
       dataStream.Write(byteArray, 0, byteArray.Length)
       ' Close the Stream object.
       dataStream.Close()
       ' Get the response.
       Dim response As WebResponse = request.GetResponse()
       ' Display the status.
       Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)
       ' Get the stream containing content returned by the server.
       dataStream = response.GetResponseStream()
       ' Open the stream using a StreamReader for easy access.
       Dim reader As New StreamReader(dataStream)
       ' Read the content.
       Dim responseFromServer As String = reader.ReadToEnd()
       ' Display the content.
       txtoutput.Text = responseFromServer
       ' Clean up the streams.
       reader.Close()
       dataStream.Close()
       response.Close()
   End Sub
 
End Class
 
 

Muchas gracias por cualquier ayuda

_katze_:
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

TrashAmbishion:
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
 
   Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
       'UploadLocalFile()
       Dim CookieJar As New CookieContainer
       Dim Url As String = "http://lok.myvnc.com/insertar-anuncio.html?isDBMode=1"
       Dim parametros As New NameValueCollection()
 
       ' Create the data we want to send
       parametros.Add("var1", "1235")
       parametros.Add("var2", "524")
       parametros.Add("var3", "Mas información para mandar")
       parametros.Add("var4", "Mas informacion para mandar")
       parametros.Add("var5", "jdueybd@gjhf.com")
       parametros.Add("var6", "123456")
       parametros.Add("var7", "654321")
       parametros.Add("var8", "Pepin")
 
       Uploaddata(CookieJar, Url, "C:\corazon.jpeg", "ad_picture_a", "image,jpeg", parametros)
   End Sub
 
'Funcion que manda la información
 
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
 
       Dim boundary As String = "---------------------------" & DateTime.Now.Ticks.ToString("x")
       Dim newLine As String = System.Environment.NewLine
       Dim boundaryBytes As Byte() = System.Text.Encoding.ASCII.GetBytes(newLine & "--" & boundary & newLine)
       Dim request As Net.HttpWebRequest = Net.WebRequest.Create(Uri)
 
       request.ContentType = "multipart/form-data; boundary=" & boundary
       request.Method = "POST"
       request.Referer = "http://lok.myvnc.com/vivienda/casa-en-la-playa/insertar-anuncio.html"
       request.Headers.Add("Accept-Encoding", "gzip, deflate")
       request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
       request.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:16.0) Gecko/20100101 Firefox/16.0"
       request.CookieContainer = containa
       request.AllowAutoRedirect = True
       request.Timeout = -1
       request.KeepAlive = True
       request.AllowWriteStreamBuffering = False
 
       Dim ms As New MemoryStream()
       Dim formDataTemplate As String = "Content-Disposition: form-data; name=""{0}""{1}{1}{2}"
 
       For Each key As String In otherParameters.Keys
           ms.Write(boundaryBytes, 0, boundaryBytes.Length)
           Dim formItem As String = String.Format(formDataTemplate, key, newLine, otherParameters(key))
           Dim formItemBytes As Byte() = System.Text.Encoding.UTF8.GetBytes(formItem)
           ms.Write(formItemBytes, 0, formItemBytes.Length)
       Next key
 
       ms.Write(boundaryBytes, 0, boundaryBytes.Length)
 
       Dim headerTemplate As String = "Content-Disposition: form-data; name=""{0}""; filename=""{1}""{2}Content-Type: {3}{2}{2}"
       Dim header As String = String.Format(headerTemplate, fileParameterName, filePath, newLine, contentType)
       Dim headerBytes As Byte() = System.Text.Encoding.UTF8.GetBytes(header)
       ms.Write(headerBytes, 0, headerBytes.Length)
 
       Dim length As Long = ms.Length
       length += New FileInfo(filePath).Length
       request.ContentLength = length
 
       Using requestStream As IO.Stream = request.GetRequestStream()
           Dim bheader() As Byte = ms.ToArray()
           requestStream.Write(bheader, 0, bheader.Length)
           Using fileStream As New IO.FileStream(filePath, IO.FileMode.Open, IO.FileAccess.Read)
 
               Dim buffer(4096) As Byte
               Dim bytesRead As Int32 = fileStream.Read(buffer, 0, buffer.Length)
 
               Do While (bytesRead > 0)
                   requestStream.Write(buffer, 0, bytesRead)
                   bytesRead = fileStream.Read(buffer, 0, buffer.Length)
               Loop
           End Using
           requestStream.Close()
       End Using
 
       Dim response As Net.WebResponse = Nothing
       Dim responseText = ""
 
       Try
 
           response = request.GetResponse()
 
           Using responseStream As IO.Stream = response.GetResponseStream()
 
               Using responseReader As New IO.StreamReader(responseStream)
 
                   responseText = responseReader.ReadToEnd()
 
               End Using
 
           End Using
 
       Catch exception As Net.WebException
 
           MsgBox(exception.Message)
 
       Finally
 
           response.Close()
           response = Nothing
           request = Nothing
       End Try
 
       Return responseText
 
   End Function
 
End Class
 
 


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...

Navegación

[0] Índice de Mensajes