Как получить числовые Коды состояния HTTP в PowerShell

Не используйте @@ ИДЕНТИФИКАЦИОННЫЕ ДАННЫЕ, однако простые, это может казаться. Это может возвратить неправильные значения.

SELECT SCOPE_IDENTITY()

, кажется, очевидный выбор.

22
задан halr9000 24 September 2009 в 07:26
поделиться

3 ответа

Используя ответы как x0n, так и joshua ewer, чтобы завершить полный круг с примером кода, я надеюсь, что это не так уж плохо :

$url = 'http://google.com'
$req = [system.Net.WebRequest]::Create($url)

try {
    $res = $req.GetResponse()
} 
catch [System.Net.WebException] {
    $res = $_.Exception.Response
}

$res.StatusCode
#OK

[int]$res.StatusCode
#200
56
ответ дан 16 October 2019 в 03:36
поделиться

I realize the question's title is about powershell, but not really what the question is asking? Either way...

The WebClient is a very dumbed down wrapper for HttpWebRequest. WebClient is great if you just doing very simple consumption of services or posting a bit of Xml, but the tradeoff is that it's not as flexible as you might want it to be. You won't be able to get the information you are looking for from WebClient.

If you need the status code, get it from the HttpWebResponse. If you were doing something like this (just posting a string to a Url) w/ WebClient:

var bytes = 
    System.Text.Encoding.ASCII.GetBytes("my xml"); 

var response = 
    new WebClient().UploadData("http://webservice.com", "POST", bytes);

then you'd do this with HttpWebRequest to get status code. Same idea, just more options (and therefore more code).

//create a stream from whatever you want to post here
var bytes = 
  System.Text.Encoding.ASCII.GetBytes("my xml"); 
var request = 
  (HttpWebRequest)WebRequest.Create("http://webservice.com");

//set up your request options here (method, mime-type, length)

//write something to the request stream
var requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);        
requestStream.Close();

var response = (HttpWebResponse)request.GetResponse();

//returns back the HttpStatusCode enumeration
var httpStatusCode = response.StatusCode;
4
ответ дан 16 October 2019 в 03:36
поделиться

Используйте перечислимый тип [system.net.httpstatuscode] .

ps> [enum]::getnames([system.net.httpstatuscode])
Continue
SwitchingProtocols
OK
Created
Accepted
NonAuthoritativeInformation
NoContent
ResetContent
...

Чтобы получить числовой код, приведите его к [int]:

ps> [int][system.net.httpstatuscode]::ok
200

Надеюсь, это поможет,

-Oisin

13
ответ дан 16 October 2019 в 03:36
поделиться
Другие вопросы по тегам:

Похожие вопросы: