PHP cURL을 사용하여 JSON 데이터를 게시하는 방법
여기 제 코드가 있습니다.
$url = 'url_to_post';
$data = array(
"first_name" => "First name",
"last_name" => "last name",
"email"=>"email@gmail.com",
"addresses" => array (
"address1" => "some address",
"city" => "city",
"country" => "CA",
"first_name" => "Mother",
"last_name" => "Lastnameson",
"phone" => "555-1212",
"province" => "ON",
"zip" => "123 ABC"
)
);
$data_string = json_encode($data);
$ch=curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, array("customer"=>$data_string));
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array(
'Content-Type:application/json',
'Content-Length: ' . strlen($data_string)
)
);
$result = curl_exec($ch);
curl_close($ch);
그리고 다른 페이지에서는 포스트 데이터를 취득하고 있습니다.
print_r ($_POST);
출력은
HTTP/1.1 200 OK
Date: Mon, 18 Jun 2012 07:58:11 GMT
Server: Apache
X-Powered-By: PHP/5.3.6
Vary: Accept-Encoding
Connection: close
Content-Type: text/html
Array ( )
따라서 내 서버에서도 적절한 데이터를 얻을 수 없습니다.그것은 빈 어레이입니다.http://docs.shopify.com/api/customer#create에서와 같이 json을 사용하여 REST를 구현하고 싶습니다.
json의 POST가 잘못되어 있습니다.그러나 그것이 맞더라도 다음 명령어를 사용하여 테스트할 수 없습니다.print_r($_POST)
(이유는 이쪽).대신 두 번째 페이지에서 POSTed json을 포함하는 를 사용하여 수신 요청을 캡처할 수 있습니다.수신한 데이터를 보다 읽기 쉬운 형식으로 표시하려면 , 다음의 순서에 따릅니다.
echo '<pre>'.print_r(json_decode(file_get_contents("php://input")),1).'</pre>';
당신의 코드에서 당신은 다음을 나타내고 있다.Content-Type:application/json
단, 모든 POST 데이터를 json-encoding하는 것은 아닙니다.단, "customer" POST 필드의 값뿐입니다.대신 다음과 같은 작업을 수행합니다.
$ch = curl_init( $url );
# Setup request to send json via POST.
$payload = json_encode( array( "customer"=> $data ) );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
# Return response instead of printing.
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
# Send request.
$result = curl_exec($ch);
curl_close($ch);
# Print response.
echo "<pre>$result</pre>";
사이드노트:직접 Shopify API와 인터페이스하지 않고 서드파티 라이브러리를 사용하면 도움이 될 수 있습니다.
$url = 'url_to_post';
$data = array("first_name" => "First name","last_name" => "last name","email"=>"email@gmail.com","addresses" => array ("address1" => "some address" ,"city" => "city","country" => "CA", "first_name" => "Mother","last_name" => "Lastnameson","phone" => "555-1212", "province" => "ON", "zip" => "123 ABC" ) );
$postdata = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);
print_r ($result);
이 암호는 나에게 효과가 있었어.한번 해봐...
교체하다
curl_setopt($ch, CURLOPT_POSTFIELDS, array("customer"=>$data_string));
포함:
$data_string = json_encode(array("customer"=>$data));
//Send blindly the json-encoded string.
//The server, IMO, expects the body of the HTTP request to be in JSON
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
당신이 말한 "다른 페이지"가 무슨 뜻인지 모르겠어요. "url_to_post"에 있는 페이지였으면 좋겠어요.그 페이지가 PHP로 쓰여져 있는 경우는, 위에서 투고한 JSON은 다음과 같이 읽힙니다.
$jsonStr = file_get_contents("php://input"); //read the HTTP body.
$json = json_decode($jsonStr);
다음 코드를 사용해 보십시오.-
$url = 'url_to_post';
$data = array("first_name" => "First name","last_name" => "last name","email"=>"email@gmail.com","addresses" => array ("address1" => "some address" ,"city" => "city","country" => "CA", "first_name" => "Mother","last_name" => "Lastnameson","phone" => "555-1212", "province" => "ON", "zip" => "123 ABC" ) );
$data_string = json_encode(array("customer" =>$data));
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
echo "$result";
첫번째,
항상 CURLOPT_CAPATH 옵션을 사용하여 증명서를 정의합니다.
POST 데이터의 전송 방법을 결정합니다.
증명서 1장
디폴트:
CURLOPT_SSL_VERIFYHOST == 2
"공통 이름의 존재를 확인하고 제공된 호스트 이름과 일치하는지 확인합니다." 및CURLOPT_VERIFYPEER == true
피어 증명서를 취득합니다.
그러면 다음 작업만 하면 됩니다.
const CAINFO = SERVER_ROOT . '/registry/cacert.pem';
...
\curl_setopt($ch, CURLOPT_CAINFO, self::CAINFO);
노동계급에서 가져온SERVER_ROOT
는 커스텀클래스로더나 다른 클래스 등과 같이 어플리케이션 부트스트레이핑 중에 정의되는 상수입니다.
잊어버려라든가 \curl_setopt($handler, CURLOPT_SSL_VERIFYHOST, 0);
또는\curl_setopt($handler, CURLOPT_SSL_VERIFYPEER, 0);
.
검색cacert.pem
이 질문에서 보듯이 거기에 있습니다.
POST 모드x 2
실제로 데이터를 게시할 때는 두 가지 모드가 있습니다.
데이터가 와 함께 전송됩니다.
Content-Type
헤더 세트multipart/form-data
또는,data는 urlencoded 문자열로,
application/x-www-form-urlencoded
부호화를 실시합니다.
첫 번째 경우 어레이를 전달하고 두 번째 경우 urlencoded 문자열을 전달합니다.
multipart/form-data
예:
$fields = array('a' => 'sth', 'b' => 'else');
$ch = \curl_init();
\curl_setopt($ch, CURLOPT_POST, 1);
\curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
application/x-www-form-urlencoded
예:
$fields = array('a' => 'sth', 'b' => 'else');
$ch = \curl_init();
\curl_setopt($ch, CURLOPT_POST, 1);
\curl_setopt($ch, CURLOPT_POSTFIELDS, \http_build_query($fields));
http_build_query
:
명령줄에서 테스트:
user@group:$ php -a
php > $fields = array('a' => 'sth', 'b' => 'else');
php > echo \http_build_query($fields);
a=sth&b=else
POST 요청의 다른 쪽 끝에는 적절한 연결 모드가 정의됩니다.
다음과 같이 시도합니다.
$url = 'url_to_post';
// this is only part of the data you need to sen
$customer_data = array("first_name" => "First name","last_name" => "last name","email"=>"email@gmail.com","addresses" => array ("address1" => "some address" ,"city" => "city","country" => "CA", "first_name" => "Mother","last_name" => "Lastnameson","phone" => "555-1212", "province" => "ON", "zip" => "123 ABC" ) );
// As per your API, the customer data should be structured this way
$data = array("customer" => $customer_data);
// And then encoded as a json string
$data_string = json_encode($data);
$ch=curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $data_string,
CURLOPT_HEADER => true,
CURLOPT_HTTPHEADER => array('Content-Type:application/json', 'Content-Length: ' . strlen($data_string)))
));
$result = curl_exec($ch);
curl_close($ch);
중요한 것은 데이터를 json_encode하는 것입니다.단, curl_setopt_array를 사용하여 어레이를 전달함으로써 모든 curl 옵션을 한 번에 설정할 수도 있습니다.
이 예를 사용해 보세요.
<?php
$url = 'http://localhost/test/page2.php';
$data = array("first_name" => "First name","last_name" => "last name","email"=>"email@gmail.com","addresses" => array ("address1" => "some address" ,"city" => "city","country" => "CA", "first_name" => "Mother","last_name" => "Lastnameson","phone" => "555-1212", "province" => "ON", "zip" => "123 ABC" ) );
$ch=curl_init($url);
$data_string = urlencode(json_encode($data));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, array("customer"=>$data_string));
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>
페이지2php 코드
<?php
$datastring = $_POST['customer'];
$data = json_decode( urldecode( $datastring));
?>
언급URL : https://stackoverflow.com/questions/11079135/how-to-post-json-data-with-php-curl
'programing' 카테고리의 다른 글
상위 행을 삭제하거나 업데이트할 수 없음: 외부 키 제약 조건이 실패합니다. (0) | 2022.12.11 |
---|---|
MySQL 테이블이 마지막으로 업데이트된 날짜를 확인하려면 어떻게 해야 합니까? (0) | 2022.12.11 |
문자열을 n자 세그먼트로 분할하려면 어떻게 해야 합니까? (0) | 2022.12.11 |
크기 자동 조정을 사용하여 텍스트 영역 작성 (0) | 2022.12.11 |
C write는 분명히 숫자를 쓰지 않는다. (0) | 2022.12.11 |