PHP 는 Http Post 를 사용 하여 JSon 대상 데이터 코드 분석 을 요청 합 니 다.

1608 단어 PHPHttpPostJson대상
프로젝트 의 필요 로 인해 PHP 는 제3자 자바/.Net 이 작성 한 Restful Api 를 호출 합 니 다.그 중 일부 인 터 페 이 스 는 POST 요청 을 보 낼 때 대상 에 게 전송 해 야 합 니 다.
Http 에서 전송 대상 의 가장 좋 은 표현 형식 은 JSON 문자열 입 니 다.그러나 매개 변수의 수신 자로 서 알려 져 야 할 것 은 JSON 입 니 다!
사실 이것 은 어렵 지 않 습 니 다.http Content-Type 헤더 메 시 지 를 보 내 면 됩 니 다.즉,'Content-Type:application/json;charset=utf-8"참조 코드 는 다음 과 같 습 니 다.

<?php
/**
 * PHP  Json    
 *
 * @param $url   url
 * @param $jsonStr    json   
 * @return array
 */
function http_post_json($url, $jsonStr)
{
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array(
      'Content-Type: application/json; charset=utf-8',
      'Content-Length: ' . strlen($jsonStr)
    )
  );
  $response = curl_exec($ch);
  $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close($ch);
 
  return array($httpCode, $response);
}
 
$url = "http://52php.cnblogs.com";
$jsonStr = json_encode(array('a' => 1, 'b' => 2, 'c' => 2));
list($returnCode, $returnContent) = http_post_json($url, $jsonStr);
API 서버 에서 클 라 이언 트 가 보 내 온"Content-Type:application/json;charset=utf-8"헤더 정보 후 http body 데이터(즉,JSon 문자열)를 클래스 대상 으로 변환 합 니 다!
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기