Ver Mensaje Individual
  #6 (permalink)  
Antiguo 02/02/2010, 13:34
jmo25
 
Fecha de Ingreso: febrero-2010
Mensajes: 3
Antigüedad: 14 años, 2 meses
Puntos: 0
Respuesta: POST en vb.net

Les adjunto el codigo de un modulo que me funciona OK.
Recibe una estructura de parametros indicando si son archivos o cadenas, los envia al servidor y retorna el objeto response.

Saludos, espero les sea de utilidad

Código vb:
Ver original
  1. Imports System.IO
  2. Imports System.Net
  3. Imports System.Net.Security
  4. Imports System
  5. Imports System.Web
  6. Imports System.Security.Cryptography.X509Certificates
  7. Imports System.Text
  8.  
  9. Module utiles
  10.     Public Enum typeParam
  11.         param_string = 0
  12.         param_file = 1
  13.     End Enum
  14.     Public Structure tParam
  15.         Dim name As String
  16.         Dim value As String
  17.         Dim type As typeParam
  18.     End Structure
  19.  
  20.  
  21.  
  22.     Public Function requestHTTP(ByVal strURL As String, ByVal params() As tParam, Optional ByVal USERNAME As String = "", _
  23.                                  Optional ByVal PSSWD As String = "", _
  24.                                  Optional ByVal Domain As String = "") As HttpWebResponse
  25.  
  26.         '****************************************************************
  27.        'Genarar datos del POST en el stream tmpStream
  28.        '****************************************************************
  29.  
  30.         'Generar limite
  31.        Dim limite As String = "----------" & DateTime.Now.Ticks.ToString("x")
  32.  
  33.         'Generar contenido del post
  34.        Dim sb As StringBuilder = New StringBuilder()
  35.         Dim paramHeader As String
  36.         Dim paramHeaderBytes As Byte()
  37.         Dim tmpStream As Stream = New MemoryStream()
  38.         Dim buffer As Byte() = {}
  39.         Dim bytesRead As Integer = 0
  40.         Dim i As Integer
  41.         'Recorre cada parametro generando el arreglo de bytes y esribiendolos en el buffer de salida
  42.        For i = 0 To UBound(params)
  43.             sb = New StringBuilder()
  44.             If params(i).type = typeParam.param_string Then
  45.                 'Si es una cadena
  46.                sb.Append("--")
  47.                 sb.Append(limite)
  48.                 sb.Append(vbNewLine)
  49.                 sb.Append("Content-Disposition: form-data; name=""")
  50.                 sb.Append(params(i).name) 'Nombre del parametro
  51.                sb.Append("""")
  52.                 sb.Append(vbNewLine)
  53.                 sb.Append(vbNewLine)
  54.                 sb.Append(params(i).value) 'Valor del parametro
  55.                sb.Append(vbNewLine)
  56.                 'Escribir la cabecera del parametro en el tmpStream
  57.                paramHeader = sb.ToString()
  58.                 paramHeaderBytes = Encoding.UTF8.GetBytes(paramHeader)
  59.                 tmpStream.Write(paramHeaderBytes, 0, paramHeaderBytes.Length)
  60.             Else
  61.                 'Si es un archivo
  62.                sb.Append("--")
  63.                 sb.Append(limite)
  64.                 sb.Append(vbNewLine)
  65.                 sb.Append("Content-Disposition: form-data; name=""")
  66.                 sb.Append(params(i).name) 'Nombre del parametro
  67.                sb.Append("""; filename=""")
  68.                 sb.Append(Path.GetFileName(params(i).value)) 'Nombre del archivo
  69.                sb.Append("""")
  70.                 sb.Append(vbNewLine)
  71.                 sb.Append("Content-Type: ")
  72.                 sb.Append("application/octet-stream")
  73.                 sb.Append(vbNewLine)
  74.                 sb.Append(vbNewLine)
  75.  
  76.                 'Escribir la cabecera del parametro en el tmpStream
  77.                paramHeader = sb.ToString()
  78.                 paramHeaderBytes = Encoding.UTF8.GetBytes(paramHeader)
  79.                 tmpStream.Write(paramHeaderBytes, 0, paramHeaderBytes.Length)
  80.  
  81.                 Dim fileStream As FileStream = New FileStream(params(i).value, FileMode.Open, FileAccess.Read)
  82.  
  83.                 'Escribir el contenido del archivo
  84.                ReDim buffer(fileStream.Length - 1)
  85.                 bytesRead = fileStream.Read(buffer, 0, buffer.Length)
  86.                 While bytesRead <> 0
  87.                     tmpStream.Write(buffer, 0, bytesRead)
  88.                     bytesRead = fileStream.Read(buffer, 0, buffer.Length)
  89.                 End While
  90.  
  91.             End If
  92.         Next
  93.  
  94.         'Crear el string de límite final como matriz de bytes
  95.        Dim limiteBytes As Byte() = Encoding.UTF8.GetBytes(vbNewLine & "--" + limite + vbNewLine)
  96.  
  97.         'Escriba el límite final
  98.        tmpStream.Write(limiteBytes, 0, limiteBytes.Length)
  99.  
  100.  
  101.         '********************************************************************
  102.        'Enviar el request
  103.        '********************************************************************
  104.  
  105.         'Cuando utiliza protocolo HTTPS necesita una función de validación de certificado
  106.        'Para este caso la función devuelve siempre true
  107.        'Si no es HTTPS no utiliza esta funcion
  108.        ServicePointManager.ServerCertificateValidationCallback = New RemoteCertificateValidationCallback(AddressOf ValidateCertificate)
  109.  
  110.         'Crear el objeto HttpWebRequest con la url de la pagina destino
  111.        Dim HttpWRequest As HttpWebRequest = HttpWebRequest.Create(strURL)
  112.         'Si se le pasaron credenciales las asigna, sino utilizar las credenciales actuales
  113.        If (USERNAME <> "") Then
  114.             Dim creds As New Net.NetworkCredential(USERNAME, PSSWD, Domain)
  115.             HttpWRequest.Credentials = creds
  116.         Else
  117.             HttpWRequest.Credentials = CredentialCache.DefaultCredentials
  118.         End If
  119.  
  120.         'Habilitar el buffer, no se envían los datos hasta la sentencia GetResponse()
  121.        HttpWRequest.AllowWriteStreamBuffering = True
  122.  
  123.         HttpWRequest.Method = "POST"
  124.  
  125.         'Asignar el contentType con el limite
  126.        HttpWRequest.ContentType = "multipart/form-data; boundary=" & limite
  127.  
  128.  
  129.         tmpStream.Seek(0, SeekOrigin.Begin)
  130.         'asignar el largo del stream
  131.        HttpWRequest.ContentLength = tmpStream.Length
  132.         Dim stream As Stream = HttpWRequest.GetRequestStream()
  133.  
  134.         ReDim buffer(tmpStream.Length - 1)
  135.         bytesRead = tmpStream.Read(buffer, 0, buffer.Length)
  136.         While bytesRead <> 0
  137.             stream.Write(buffer, 0, bytesRead)
  138.             bytesRead = tmpStream.Read(buffer, 0, buffer.Length)
  139.         End While
  140.  
  141.         Dim Response As HttpWebResponse = Nothing
  142.         Try
  143.             Response = HttpWRequest.GetResponse()
  144.         Catch ex As Exception
  145.             Debug.Print(ex.Message)
  146.         End Try
  147.         Return Response
  148.     End Function
  149.  
  150.    
  151.  
  152.  
  153.     Private Function ValidateCertificate(ByVal sender As Object, ByVal certificate As X509Certificate, ByVal chain As X509Chain, ByVal sslPolicyErrors As SslPolicyErrors) As Boolean
  154.         Dim validationResult As Boolean
  155.         validationResult = True
  156.         '
  157.        ' policy code here ...
  158.        '
  159.        Return validationResult
  160.     End Function
  161.  
  162.     Function readFileHTTP(ByVal strURL As String) As Byte()
  163.         Dim res() As Byte = {}
  164.         Try
  165.             Dim fr As System.Net.HttpWebRequest
  166.             Dim targetURI As New Uri(strURL)
  167.             fr = DirectCast(System.Net.HttpWebRequest.Create(targetURI), System.Net.HttpWebRequest)
  168.             If (fr.GetResponse().ContentLength > 0) Then
  169.                 Dim str As New System.IO.StreamReader(fr.GetResponse().GetResponseStream())
  170.                 res = System.Text.ASCIIEncoding.ASCII.GetBytes(str.ReadToEnd())
  171.                 str.Close()
  172.             End If
  173.         Catch ex As System.Net.WebException
  174.         End Try
  175.  
  176.         Return res
  177.     End Function
  178.  
  179.  
  180. End Module