VB.NET HTTP POST with ip and tcp port

32 Views Asked by At

I have this sub that make a POST request to a PLC board

Public Sub httpPOST_CCN(ip As String, user As String, pwd As String, digout As Integer, sec As Integer, dec As Integer, verso As String, Optional causale As String = "", Optional ultimaTarga As String = "", Optional ultimoBadge As String = "")
        Dim CookieJar As New CookieContainer
        Dim url As String = String.Format("http://{0}/goform/UserLogin", ip)
        Dim postData As String = String.Format("username={0}&pwd={1}", user, pwd)

        ' Effettua la prima chiamata POST per l'autenticazione
        Dim reader As StreamReader

        Dim Request As HttpWebRequest = HttpWebRequest.Create(url)

        Request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14"
        Request.CookieContainer = CookieJar
        Request.AllowAutoRedirect = False
        Request.ContentType = "application/x-www-form-urlencoded"
        Request.Method = "POST"
        Request.ContentLength = postData.Length
        'Request.KeepAlive = False

        Dim requestStream As Stream = Request.GetRequestStream()
        Dim postBytes As Byte() = Encoding.ASCII.GetBytes(postData)

        requestStream.Write(postBytes, 0, postBytes.Length)
        requestStream.Close()

        Dim Response As HttpWebResponse = Request.GetResponse()

        For Each tempCookie In Response.Cookies
            CookieJar.Add(tempCookie)
        Next

        reader = New StreamReader(Response.GetResponseStream())
        Response.Close()

        ' Chiamata POST successiva
        Dim outputUrl As String = String.Format("http://{0}/goform/con_SetOutput?secondi={1}&decimi={2}&outputNumber={3}", ip, sec, dec, digout)

        Dim RequestOut As HttpWebRequest = HttpWebRequest.Create(outputUrl)
        RequestOut.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14"
        RequestOut.AllowAutoRedirect = False
        RequestOut.CookieContainer = CookieJar
        'RequestOut.KeepAlive = False

        Dim ResponseOut As HttpWebResponse = RequestOut.GetResponse()

        reader = New StreamReader(ResponseOut.GetResponseStream())
        ResponseOut.Close()


    End Sub

It works ok when the ip parameter is inside the local network without specifying the tcp port, if I pass to it an external address with specific tcp port, like this:

httpPOST_CCN("X.X.X.X:8000", "user", "pass", 1, 1, 0, 0)

it gives me a Null Request because it's not reachable from whitin the code, but I know I can reach it on browser. Is this because of the port? What should I change to make it work? Thanks

EDIT: I'm thinking that maybe it fails because the board took too long to send a response... so the question should be: how can I wait until the connection is made and then proceed?

0

There are 0 best solutions below