programing

LWP로 JSON POST 요청을 하려면 어떻게 해야 하나요?

instargram 2023. 3. 8. 20:36
반응형

LWP로 JSON POST 요청을 하려면 어떻게 해야 하나요?

https://orbit.theplanet.com/Login.aspx?url=/Default.aspx(사용자 이름/암호 조합 사용)에서 로그인하려고 하면 로그인 자격 증명이 별도의 POST 데이터 집합이 아닌 JSON 문자열로 전송되고 일반 키=값 쌍이 없음을 알 수 있습니다.

구체적으로는, 다음과 같은 것이 아닙니다.

username=foo&password=bar

또는 다음과 같은 경우도 있습니다.

json={"username":"foo","password":"bar"}

다음과 같은 것이 있습니다.

{"username":"foo","password":"bar"}

이러한 요청을 수행할 수 있습니까?LWP또는 대체 모듈?나는 그것을 할 준비가 되어 있다.IO::Socket가능하다면 좀 더 높은 수준의 것을 선호합니다.

HTTP 요청을 수동으로 작성하여 LWP에 전달해야 합니다.다음과 같은 방법이 필요합니다.

my $uri = 'https://orbit.theplanet.com/Login.aspx?url=/Default.aspx';
my $json = '{"username":"foo","password":"bar"}';
my $req = HTTP::Request->new( 'POST', $uri );
$req->header( 'Content-Type' => 'application/json' );
$req->content( $json );

그런 다음 LWP를 사용하여 요청을 실행할 수 있습니다.

my $lwp = LWP::UserAgent->new;
$lwp->request( $req );

그것을 본문으로 하여 POST 요청을 작성하여 LWP에 전달하기만 하면 됩니다.

my $req = HTTP::Request->new(POST => $url);
$req->content_type('application/json');
$req->content($json);

my $ua = LWP::UserAgent->new; # You might want some options here
my $res = $ua->request($req);
# $res is an HTTP::Response, see the usual LWP docs.

이 페이지는 익명으로 입력된 (이름 없이) JSON 형식일 뿐입니다.

$ua->post url, ..., Content => $content)를 사용할 수 있어야 합니다.이것에 의해, HTTP::Request::평범하다.

use LWP::UserAgent;

my $url = 'https://orbit.theplanet.com/Login.aspx?url=/Default.aspx';
my $json = '{"username": "foo", "password": "bar"}';

my $ua = new LWP::UserAgent();
$response = $ua->post($url, Content => $json);

if ( $response->is_success() ) {
    print("SUCCESSFUL LOGIN!\n");
}
else {
    print("ERROR: " . $response->status_line());
}

또는 JSON 입력에 해시를 사용할 수도 있습니다.

use JSON::XS qw(encode_json);

...

my %json;
$json{username} = "foo";
$json{password} = "bar";

...

$response = $ua->post($url, Content => encode_json(\%json));

WWW::메커니즘을 사용하려면 게시 전에 '콘텐츠 유형' 헤더를 설정할 수 있습니다.

$mech->add_header( 
'content-type' => 'application/json'
);

$mech->post($uri, Content => $json);

언급URL : https://stackoverflow.com/questions/4199266/how-can-i-make-a-json-post-request-with-lwp

반응형