2013-03-06 6 views
1

다음 페이지가 있습니다.PHP의 cURL을 통한 JSON이 작동하지 않습니다.

페이지 json.php :

$json_data = array(
    'first_name' => 'John', 
    'last_name' => 'Doe', 
    'birthdate' => '12/02/1977', 
    'files'  => array(
     array(
      'name' => 'file1.zip', 
      'status' => 'good' 
     ), 
     array(
      'name' => 'file2.zip', 
      'status' => 'good' 
     ) 
    ) 
); 

$url = 'http://localhost/test.php'; 

$content = json_encode($json_data); 

$curl = curl_init(); 

curl_setopt($curl, CURLOPT_URL, $url); 
curl_setopt($curl, CURLOPT_HEADER, false); 
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($curl, CURLOPT_HTTPHEADER, 
    array(
     "Content-type: application/json", 
     "Content-Length: " . strlen($content) 
    ) 
); 
curl_setopt($curl, CURLOPT_POST, true); 
curl_setopt($curl, CURLOPT_POSTFIELDS, 'json=' . urlencode($content)); 
curl_setopt($curl, CURLINFO_HEADER_OUT, true); 

$json_response = curl_exec($curl); 

$status  = curl_getinfo($curl, CURLINFO_HTTP_CODE); 
$header_sent = curl_getinfo($curl, CURLINFO_HEADER_OUT); 

curl_close($curl); 

echo $header_sent; 
echo '<br>'; 
echo $status; 
echo '<br>'; 
echo $json_response; 

페이지 test.php :

내가 브라우저에서 json.php 전화 드렸습니다
echo '<pre>'; 
print_r($_POST); 
echo '</pre>'; 

, 나는 다음과 같은 결과를 얻을 :

POST /json.php HTTP/1.1 Host: localhost Accept: */* Content-type: application/json Content-Length: 150 
200 

Array 
(
) 

왜 보내려는 POST 문자열을 볼 수 없습니까?

편집 :

내가 (@의 landons의 의견에 따라)을 Content-type: application/json 헤더를 설정하지 않은 경우, 나는 다음과 같은 결과를 얻을 :

이 가
POST /ddabvd/widendcm/widendcm-finished.php HTTP/1.1 Host: localhost Accept: */* Content-Length: 150 Content-Type: application/x-www-form-urlencoded 
200 
Array 
(
    [json] => {"first_name":"John","last_name":"Doe","birthdate":"12\/02\/1977","files":[{"name": 
) 
+1

application/json Content-type 헤더를 보내지 않으면 어떻게 될까요? – landons

+0

@landons 문자열이 잘립니다. (내 업데이트를 참조하십시오.) – Alex

+2

멀티 파트가 아닌 비 URL 인코딩 된 내용에'$ _POST' 배열을 사용하지 마십시오. 'var_dump (file_get_contents ('php : // input'));' – Wrikken

답변

2

PHP를 사용하지 않습니다 그것은 내부 요청 구문 분석입니다 콘텐츠 유형이 브라우저 내부에서 양식을 게시 할 때 사용되는 두 가지 공식 콘텐츠 유형 중 하나로 설정되지 않은 경우 POST 요청에 사용됩니다. (예 : 허용되는 콘텐츠 유형은 multipart/form-data이며 파일 업로드에 자주 사용되며 기본값은 application/x-www-form-urlencoded).

다른 콘텐츠 유형을 사용하려는 경우, 예를 들어 php://input에서 요청 본문을 가져올 때 자신을 모두 파싱해야합니다.

사실 현재 콘텐츠 유형이 잘못되었습니다. 데이터가 json={...}이므로 json으로 구문 분석 할 때 올바르지 않으므로 application/json이 아닙니다.

+0

이것을 추가하려면 cURL의 게시 필드가 아닌 메시지의 본문으로 컨텐츠를 보내야합니다. 이것은 JSON을 전달하는 RESTful 서비스에서 더 일반적입니다. –

관련 문제