使用cuRL发布url的数据

时间:2017-07-23 15:45:56

标签: php curl

我正在尝试将一些数据发送到curl URL以获取密钥。

curl命令是:

curl -X POST "http://website.com/api/open/oauth/token" -H "accept: application/json" -H "Authorization: xx:xxxxxxxxxxxxxxxx" -H "content-type: application/x-www-form-urlencoded" -d "grant_type=password&username=xxx@yahoo.com&password=xxxx"

知道如何查看php代码以获取响应密钥吗?

2 个答案:

答案 0 :(得分:2)

你可以这样试试,

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "http://website.com/api/open/oauth/token");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=password&username=xxx@yahoo.com&password=xxxx");
curl_setopt($ch, CURLOPT_POST, 1);

$headers = array();
$headers[] = "Accept: application/json";
$headers[] = "Authorization: xx:xxxxxxxxxxxxxxxx";
$headers[] = "Content-Type: application/x-www-form-urlencoded";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close ($ch);

答案 1 :(得分:1)

使用cURL,你可以这样做:

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "http://website.com/api/open/oauth/token",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "grant_type=password&username=xxx%40yahoo.com&password=xxxx",
  CURLOPT_HTTPHEADER => array(
    "accept: application/json",
    "authorization: xx:xxxxxxxxxxxxxxxx",
    "cache-control: no-cache",
    "content-type: application/x-www-form-urlencoded",
    "postman-token: ac46b74a-6b24-85a4-36ea-4867a3bd3eda"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

您还可以使用HttpRequest类:

<?php

$request = new HttpRequest();
$request->setUrl('http://website.com/api/open/oauth/token');
$request->setMethod(HTTP_METH_POST);

$request->setHeaders(array(
  'postman-token' => '67cba408-41b5-7c86-568f-437e27abfa08',
  'cache-control' => 'no-cache',
  'content-type' => 'application/x-www-form-urlencoded',
  'authorization' => 'xx:xxxxxxxxxxxxxxxx',
  'accept' => 'application/json'
));

$request->setContentType('application/x-www-form-urlencoded');
$request->setPostFields(array(
  'grant_type' => 'password',
  'username' => 'xxx@yahoo.com',
  'password' => 'xxxx'
));

try {
  $response = $request->send();

  echo $response->getBody();
} catch (HttpException $ex) {
  echo $ex;
}