Using System.Net.WebRequest Class without FQDN

Welcome Forums General PowerShell Q&A Using System.Net.WebRequest Class without FQDN

This topic contains 2 replies, has 3 voices, and was last updated by

 
Participant
4 years, 3 months ago.

  • Author
    Posts
  • #11586

    Participant
    Points: 0
    Rank: Member

    So, I'm running into a strange issue I hope someone can shed some light on. I'm using the following to build my HTTPS request to a web server:

    $req = [System.Net.WebRequest]::Create("https://" + $script:Server + $uri)
    $req.Method = $method
    $req.ContentType = "application/json"
    $req.Accept = "application/json"
    $req.Headers.Item("accept-language") = "en"
    $req.Headers.Item("accept-encoding") = "gzip, deflate"
            if ($body) {
                if ($method -eq "PUT") {
                    #Handle eTags from connection manager
                    $req.Headers.Item("If-match") = $body.etag
                    }
                #Create a new stream writer to write the json to the request stream.
    		    $js = $body | ConvertTo-Json -Depth 99 -Compress
    		    if ($body.GetType().ToString() -eq "System.Object[]") {
    			    $js = "[" + $js + "]"
    			    }
    		    "Request Body: " + $js | Write-Debug 
    		    $stream = New-Object IO.StreamWriter $req.GetRequestStream()
    		    $stream.AutoFlush = $True
    		    $stream.WriteLine($js)
    		    $stream.Close()
            }
    try { 
                $script:lastWebResponse = $req.GetResponse()
    }
     } catch [Net.WebException] { #some code to return error}
    
    

    If I pass $script:Server = "Hostname", the request is never sent and simply times out. If I use either the FQDN (e.g. "hostname.domain.com") or IP Address, the connection is made successfully. Is there a problem with System.Net.WebRequest where it will only accept an FQDN or IP Address, and not the hostname? The system where I'm executing this script from is a member of the same Active Directory domain, and nslookup of "hostname" resolves to the same IP Address or FQDN I could substitute with. But I'd like my script to accept a hostname, and not require an FQDN or IP Address of the target server.

    Oh, and I'm using PowerShell 3 on Windows Server 2008 R2.

  • #18827

    Keymaster
    Points: 1,704
    Helping HandTeam Member
    Rank: Community Hero

    It needs to be able to resolve the name via DNS – it can't do a NetBIOS broadcast or anything. I'd need to do a network trace and see what was happening, but I'm guessing the web request stack isn't able to resolve just a hostname.

    (sorry for the delay – going through old unanswered posts today)

  • #18867

    Participant
    Points: 0
    Rank: Member

    Try to add netBIOS (short name) into "hosts" file and test it. If it works then it's problem in DNS resolution.

The topic ‘Using System.Net.WebRequest Class without FQDN’ is closed to new replies.