JSON에서 Guzle을 사용하여 POST 요청을 보내려면 어떻게 해야 하나요?
할 수 있는 올바른 방법 아는 사람?post
JSON 사용Guzzle
?
$request = $this->client->post(self::URL_REGISTER,array(
'content-type' => 'application/json'
),array(json_encode($_POST)));
나는 그것을 받았다.internal server error
서버로부터의 응답.Chrome을 사용하여 동작합니다.Postman
.
Guzzle 5, 6, 7의 경우 다음과 같이 수행합니다.
use GuzzleHttp\Client;
$client = new Client();
$response = $client->post('url', [
GuzzleHttp\RequestOptions::JSON => ['foo' => 'bar'] // or 'json' => [...]
]);
단순하고 기본적인 방법(guzle6):
$client = new Client([
'headers' => [ 'Content-Type' => 'application/json' ]
]);
$response = $client->post('http://api.com/CheckItOutNow',
['body' => json_encode(
[
'hello' => 'World'
]
)]
);
응답 상태 코드와 본문의 내용을 얻으려면 다음을 수행합니다.
echo '<pre>' . var_export($response->getStatusCode(), true) . '</pre>';
echo '<pre>' . var_export($response->getBody()->getContents(), true) . '</pre>';
거즐 <= 4:
미가공 포스트 요구이므로 본문에 JSON을 삽입하면 문제가 해결됩니다.
$request = $this->client->post(
$url,
[
'content-type' => 'application/json'
],
);
$request->setBody($data); #set body!
$response = $request->send();
이것은 나에게 효과가 있었다(Guzle 6 사용)
$client = new Client();
$result = $client->post('http://api.example.com', [
'json' => [
'value_1' => 'number1',
'Value_group' =>
array("value_2" => "number2",
"value_3" => "number3")
]
]);
echo($result->getBody()->getContents());
$client = new \GuzzleHttp\Client();
$body['grant_type'] = "client_credentials";
$body['client_id'] = $this->client_id;
$body['client_secret'] = $this->client_secret;
$res = $client->post($url, [ 'body' => json_encode($body) ]);
$code = $res->getStatusCode();
$result = $res->json();
하드코드를 사용하여json
Atribute as key, 또는 편리하게 사용할 수 있습니다.GuzzleHttp\RequestOptions::JSON
일정한.
다음은 하드코드 사용 예시입니다.json
스트링
use GuzzleHttp\Client;
$client = new Client();
$response = $client->post('url', [
'json' => ['foo' => 'bar']
]);
「Docs」를 참조해 주세요.
$client = new \GuzzleHttp\Client(['base_uri' => 'http://example.com/api']);
$response = $client->post('/save', [
'json' => [
'name' => 'John Doe'
]
]);
return $response->getBody();
이것은, Guzzle 6.2에서는 유효합니다.
$gClient = new \GuzzleHttp\Client(['base_uri' => 'www.foo.bar']);
$res = $gClient->post('ws/endpoint',
array(
'headers'=>array('Content-Type'=>'application/json'),
'json'=>array('someData'=>'xxxxx','moreData'=>'zzzzzzz')
)
);
문서 guzzle에 따라 json_encode를 수행합니다.
$client->요청 솔루션('POST',...
사용하시는 분$client->request
JSON 요청을 작성하는 방법은 다음과 같습니다.
$client = new Client();
$res = $client->request('POST', "https://some-url.com/api", [
'json' => [
'paramaterName' => "parameterValue",
'paramaterName2' => "parameterValue2",
]
'headers' => [
'Content-Type' => 'application/json',
]
]);
PHP 버전: 5.6
Symfony 버전: 2.3
거즐: 5.0
저는 최근에 Guzzle과 json을 보낸 경험이 있습니다.Symfony 2.3을 사용하기 때문에 Guzle 버전은 조금 더 오래된 버전일 수 있습니다.
디버깅 모드 사용방법도 알려드리겠습니다.요구는 전송 전에 확인하실 수 있습니다.
아래와 같이 요청을 했을 때, 성공적인 답변을 받았습니다.
use GuzzleHttp\Client;
$headers = [
'Authorization' => 'Bearer ' . $token,
'Accept' => 'application/json',
"Content-Type" => "application/json"
];
$body = json_encode($requestBody);
$client = new Client();
$client->setDefaultOption('headers', $headers);
$client->setDefaultOption('verify', false);
$client->setDefaultOption('debug', true);
$response = $client->post($endPoint, array('body'=> $body));
dump($response->getBody()->getContents());
@user3379466은 맞는데, 여기서는 완전히 다시 씁니다.
-package that you need:
"require": {
"php" : ">=5.3.9",
"guzzlehttp/guzzle": "^3.8"
},
-php code (Digest is a type so pick different type if you need to, i have to include api server for authentication in this paragraph, some does not need to authenticate. If you use json you will need to replace any text 'xml' with 'json' and the data below should be a json string too):
$client = new Client('https://api.yourbaseapiserver.com/incidents.xml', array('version' => 'v1.3', 'request.options' => array('headers' => array('Accept' => 'application/vnd.yourbaseapiserver.v1.1+xml', 'Content-Type' => 'text/xml'), 'auth' => array('username@gmail.com', 'password', 'Digest'),)));
$url = "https://api.yourbaseapiserver.com/incidents.xml";
$data = '<incident>
<name>Incident Title2a</name>
<priority>Medium</priority>
<requester><email>dsss@mail.ca</email></requester>
<description>description2a</description>
</incident>';
$request = $client->post($url, array('content-type' => 'application/xml',));
$request->setBody($data); #set body! this is body of request object and not a body field in the header section so don't be confused.
$response = $request->send(); #you must do send() method!
echo $response->getBody(); #you should see the response body from the server on success
die;
--- 필요한 * Guzzle 6 * --- 패키지용 솔루션:
"require": {
"php" : ">=5.5.0",
"guzzlehttp/guzzle": "~6.0"
},
$client = new Client([
// Base URI is used with relative requests
'base_uri' => 'https://api.compay.com/',
// You can set any number of default request options.
'timeout' => 3.0,
'auth' => array('you@gmail.ca', 'dsfddfdfpassword', 'Digest'),
'headers' => array('Accept' => 'application/vnd.comay.v1.1+xml',
'Content-Type' => 'text/xml'),
]);
$url = "https://api.compay.com/cases.xml";
$data string variable is defined same as above.
// Provide the body as a string.
$r = $client->request('POST', $url, [
'body' => $data
]);
echo $r->getBody();
die;
이것을 사용하면 효과가 있습니다.
$auth = base64_encode('user:'.config('mailchimp.api_key'));
//API URL
$urll = "https://".config('mailchimp.data_center').".api.mailchimp.com/3.0/batches";
//API authentication Header
$headers = array(
'Accept' => 'application/json',
'Authorization' => 'Basic '.$auth
);
$client = new Client();
$req_Memeber = new Request('POST', $urll, $headers, $userlist);
// promise
$promise = $client->sendAsync($req_Memeber)->then(function ($res){
echo "Synched";
});
$promise->wait();
저는 매우 안정적으로 작동하는 다음 코드를 사용합니다.
JSON 데이터는 파라미터 $request로 전달되며 특정 요청 유형은 변수 $searchType으로 전달됩니다.
이 코드에는 false를 반환하는 실패 또는 비활성 콜을 검출하여 보고하는 트랩이 포함되어 있습니다.
콜이 성공했을 경우 json_displaces ($result->getBody(), $return=true)는 결과 배열을 반환합니다.
public function callAPI($request, $searchType) {
$guzzleClient = new GuzzleHttp\Client(["base_uri" => "https://example.com"]);
try {
$result = $guzzleClient->post( $searchType, ["json" => $request]);
} catch (Exception $e) {
$error = $e->getMessage();
$error .= '<pre>'.print_r($request, $return=true).'</pre>';
$error .= 'No returnable data';
Event::logError(__LINE__, __FILE__, $error);
return false;
}
return json_decode($result->getBody(), $return=true);
}
@user3379466으로부터의 응답은, 다음의 설정에 의해서 동작시킬 수 있습니다.$data
다음과 같습니다.
$data = "{'some_key' : 'some_value'}";
프로젝트에 필요한 것은 변수를 json 문자열 내의 배열에 삽입하는 것이었습니다.저는 다음과 같이 했습니다(이것이 도움이 되는 경우).
$data = "{\"collection\" : [$existing_variable]}";
그래서...$existing_variable
예를 들어 90210이면 다음과 같이 됩니다.
echo $data;
//{"collection" : [90210]}
또, 주의할 필요가 있는 것은, 다음과 같은 설정도 필요하게 되는 것입니다.'Accept' => 'application/json'
그리고 만약 당신이 치게 될 끝점이 그런 것에 대해 신경 쓸 때를 대비해서도요.
위의 답변은 왠지 통하지 않았다.하지만 이건 나한테 잘 먹힌다.
$client = new Client('' . $appUrl['scheme'] . '://' . $appUrl['host'] . '' . $appUrl['path']);
$request = $client->post($base_url, array('content-type' => 'application/json'), json_encode($appUrl['query']));
언급URL : https://stackoverflow.com/questions/22244738/how-can-i-use-guzzle-to-send-a-post-request-in-json
'programing' 카테고리의 다른 글
Python 변수의 유형을 확인하는 가장 좋은(자동) 방법은 무엇입니까? (0) | 2022.12.11 |
---|---|
데이터 URI를 파일로 변환한 후 FormData에 추가 (0) | 2022.12.11 |
포스트백 실행 실패: (2031) 준비된 문의 매개 변수에 대한 데이터가 제공되지 않았습니다. (0) | 2022.12.11 |
MVC는 JSF MVC 프레임워크에서 어떤 컴포넌트입니까? (0) | 2022.12.11 |
Vue + Django 템플릿 언어를 사용할 때 이중 괄호 문제는 어떻게 해결합니까? (0) | 2022.12.11 |