programing

PowerShell에서 숫자 HTTP 상태 코드를 가져오는 방법

starjava 2023. 8. 30. 21:04
반응형

PowerShell에서 숫자 HTTP 상태 코드를 가져오는 방법

PowerShell에서 웹 클라이언트를 구축하는 몇 가지 좋은 방법을 알고 있습니다.NET 클래스 시스템.Net.Web Client 및 시스템.Net.HttpWebRequest 또는 COM 개체 Msxml2.XMLHTTP.제가 알기로는 숫자 상태 코드(예: 200, 404)에 액세스할 수 있는 유일한 것은 마지막 COM 개체입니다.제가 가지고 있는 문제는 작동 방식이 마음에 들지 않고 COM 개체가 거기에 있다는 것에 의존하는 것이 싫다는 것입니다.또한 Microsoft가 보안 취약점 등으로 인해 COM 개체(ActiveX kill bit)를 때때로 죽이기로 결정할 것이라는 것도 알고 있습니다.

또 있나요?내가 빠진 NET 방법?상태 코드가 이 두 개체 중 하나에 있는데 어떻게 해야 할지 모르겠습니다.

x0n과 joshuaewer의 답변을 모두 사용하여 코드 예제와 함께 완전한 원을 그리 나쁘지 않은 형식으로 제공하기를 바랍니다.

$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

사용[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

이게 도움이 되길 바랍니다.

-오이신

저는 질문의 제목이 파워셸에 관한 것이라는 것을 알고 있지만, 질문이 실제로 무엇을 묻는 것이 아닌가요?어느 쪽이든...

WebClient는 HttpWebRequest에 대한 매우 덤다운 래퍼입니다.WebClient는 서비스를 매우 단순하게 사용하거나 약간의 Xml을 게시하는 것만으로도 유용하지만, 원하는 만큼 유연하지 않다는 것이 단점입니다.Web Client에서 찾고 있는 정보를 가져올 수 없습니다.

상태 코드가 필요한 경우 HttpWebResponse에서 가져옵니다.WebClient를 사용하여 다음과 같은 작업(Url에 문자열만 게시)을 수행하는 경우:

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

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

상태 코드를 가져오기 위해 HttpWebRequest로 이 작업을 수행합니다.동일한 아이디어, 더 많은 옵션(따라서 더 많은 코드)입니다.

//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;

그것은 매우 쉬워 보입니다.

$wc = New-Object NET.WebClient
$wc.DownloadString($url)
$wc.ResponseHeaders.Item("status")

ResponseHeaders 속성에서 사용 가능한 다른 응답 헤더(예: 내용 유형, 내용 길이, x-powered-by 등)를 찾고 Item() 메서드를 통해 검색할 수 있습니다.

하지만 아래에 롭이 언급한 것처럼 슬프게도, 상태 속성은 여기서 사용할 수 없습니다.

언급URL : https://stackoverflow.com/questions/1473358/how-to-obtain-numeric-http-status-codes-in-powershell

반응형