programing

컬 및 PHP - PUT, POST, GET에서 컬을 통해 json을 전달하려면 어떻게 해야 합니까?

codeshow 2023. 7. 31. 21:59
반응형

컬 및 PHP - PUT, POST, GET에서 컬을 통해 json을 전달하려면 어떻게 해야 합니까?

저는 그것을 위해 Rest API를 구축하는 작업을 해왔고 CRUD에 매우 쉬운 명령줄의 컬을 사용하여 테스트를 진행하고 있습니다.

명령줄에서 이 전화를 성공적으로 걸 수 있습니다.

curl -u username:pass -X GET http://api.mysite.com/pet/1
curl -d '{"dog":"tall"}' -u username:pass -X GET http://api.mysite.com/pet
curl -d '{"dog":"short"}' -u username:pass -X POST http://api.mysite.com/pet
curl -d '{"dog":"tall"}' -u username:pass -X PUT http://api.mysite.com/pet/1

위의 호출은 명령줄에서 하기 쉽고 내 api에서 잘 작동하지만, 이제는 PHP를 사용하여 컬을 만들고 싶습니다.보시다시피, 저는 json 문자열로 데이터를 전달합니다.저는 여기저기 읽어보았고 아마도 POST를 할 수 있고 POST 필드를 포함할 수 있을 것이라고 생각하지만 GET으로 http 본문 데이터를 전달하는 방법을 찾지 못했습니다.제가 보는 모든 것은 URL에 첨부해야 한다고 되어 있지만, 명령줄 양식에서는 그렇게 보이지 않습니다.어쨌든, 저는 누군가가 여기 PHP로 이 네 가지 작업을 하는 올바른 방법을 한 페이지에 써주면 좋겠습니다.컬과 php로 가장 간단한 방법을 알고 싶습니다.내 php api가 php://input로 모든 것을 캡처하기 때문에 http 본문을 통해 모든 것을 전달해야 할 것 같습니다.

놓다

$data = array('username'=>'dog','password'=>'tall');
$data_json = json_encode($data);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_json)));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response  = curl_exec($ch);
curl_close($ch);

포스트.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response  = curl_exec($ch);
curl_close($ch);

GET See @Dan H 답변

삭제

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response  = curl_exec($ch);
curl_close($ch);

작은 라이브러리를 사용할 수 있습니다. https://github.com/ledfusion/php-rest-curl

전화 걸기는 다음과 같이 간단합니다.

// GET
$result = RestCurl::get($URL, array('id' => 12345678));

// POST
$result = RestCurl::post($URL, array('name' => 'John'));

// PUT
$result = RestCurl::put($URL, array('$set' => array('lastName' => "Smith")));

// DELETE
$result = RestCurl::delete($URL); 

$result 변수의 경우:

  • $result['status']는 HTTP 응답 코드입니다.
  • $result['data'] JSON 응답이 구문 분석된 배열
  • $result['message'] 응답 헤더가 있는 문자열

도움이 되길 바랍니다.

나 자신을 위해서, 나는 URL에 그것을 인코딩하고 목적지 페이지에서 $_GET를 사용합니다.예를 들어 다음과 같은 대사가 있습니다.

$ch = curl_init();
$this->json->p->method = "whatever";
curl_setopt($ch, CURLOPT_URL, "http://" . $_SERVER['SERVER_NAME'] . $this->json->path . '?json=' . urlencode(json_encode($this->json->p)));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);

편집: 대상 스니펫을 추가하는 중... (OPs 요청 시 위에 EDIT 2가 추가됨)

<?php
if(!isset($_GET['json']))
    die("FAILURE");
$json = json_decode($_GET['json']);
$method = $json->method;
...
?>

Elastic SQL 플러그인으로 작업하고 있었습니다.쿼리는 아래와 같이 cURL을 사용하여 GET 메서드로 수행됩니다.

curl -XGET http://localhost:9200/_sql/_explain -H 'Content-Type: application/json' \
-d 'SELECT city.keyword as city FROM routes group by city.keyword order by city'

기본 인증 세트로 역방향 프록시를 수행하여 공용 서버에서 사용자 지정 포트를 노출했습니다.

이 코드는 기본 인증 헤더와 함께 잘 작동합니다.

$host = 'http://myhost.com:9200';
$uri = "/_sql/_explain";
$auth = "john:doe";
$data = "SELECT city.keyword as city FROM routes group by city.keyword order by city";

function restCurl($host, $uri, $data = null, $auth = null, $method = 'DELETE'){
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $host.$uri);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    if ($method == 'POST')
        curl_setopt($ch, CURLOPT_POST, 1);
    if ($auth)
        curl_setopt($ch, CURLOPT_USERPWD, $auth);
    if (strlen($data) > 0)
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data);

    $resp  = curl_exec($ch);
    if(!$resp){
        $resp = (json_encode(array(array("error" => curl_error($ch), "code" => curl_errno($ch)))));
    }   
    curl_close($ch);
    return $resp;
}

$resp = restCurl($host, $uri); //DELETE
$resp = restCurl($host, $uri, $data, $auth, 'GET'); //GET
$resp = restCurl($host, $uri, $data, $auth, 'POST'); //POST
$resp = restCurl($host, $uri, $data, $auth, 'PUT'); //PUT

curl_setopt 속성을 하나 더 설정합니다($ch, CURLOPT_SSL_VERIFIPEER, false);

언급URL : https://stackoverflow.com/questions/21271140/curl-and-php-how-can-i-pass-a-json-through-curl-by-put-post-get

반응형