source

php를 사용하여 json 게시물 보내기

manysource 2022. 11. 3. 21:57

php를 사용하여 json 게시물 보내기

다음과 같은 json 데이터가 있습니다.

{ 
    userID: 'a7664093-502e-4d2b-bf30-25a2b26d6021',
    itemKind: 0,
    value: 1,
    description: 'Saude',
    itemID: '03e76d0a-8bab-11e0-8250-000c29b481aa'
}

json URL: http://domain/OnLeagueRest/resources/onLeague/Account/CreditAccount에 투고해야 합니다.

php를 사용하여 어떻게 이 게시 요청을 보낼 수 있습니까?

이를 위해 CURL을 사용할 수 있습니다.다음 코드 예를 참조하십시오.

$url = "your url";    
$content = json_encode("your data to be sent");

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
        array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);

$json_response = curl_exec($curl);

$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ( $status != 201 ) {
    die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}


curl_close($curl);

$response = json_decode($json_response, true);

외부 의존관계 또는 라이브러리를 사용하지 않는 경우:

$options = array(
  'http' => array(
    'method'  => 'POST',
    'content' => json_encode( $data ),
    'header'=>  "Content-Type: application/json\r\n" .
                "Accept: application/json\r\n"
    )
);

$context  = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result );

$response는 객체입니다.속성에 정상적으로 액세스 할 수 있습니다.예를 들어 $response->...

여기서 $data는 데이터를 포함하는 배열입니다.

$data = array(
  'userID'      => 'a7664093-502e-4d2b-bf30-25a2b26d6021',
  'itemKind'    => 0,
  'value'       => 1,
  'description' => 'Boa saudaÁ„o.',
  'itemID'      => '03e76d0a-8bab-11e0-8250-000c29b481aa'
);

경고: php.ini에서 allow_url_fopen 설정이 Off로 설정되어 있으면 작동하지 않습니다.

WordPress용으로 개발 중인 경우 제공된 API를 사용하는 것을 고려하십시오.https://developer.wordpress.org/plugins/http-api/

file_get_contents 솔루션은 서버가 HTTP 헤더에서 Connection: close를 반환할 때처럼 연결을 닫지 않습니다.

한편, CURL 솔루션은 PHP 스크립트가 응답을 기다려 차단되지 않도록 연결을 종료합니다.

CURL luke :) 정말, 그것은 그것을 하는 가장 좋은 방법 중 하나이며, 당신은 답을 얻을 수 있습니다.

언급URL : https://stackoverflow.com/questions/6213509/send-json-post-using-php