简体   繁体   English

在PHP curl调用方面需要帮助

[英]Need assistance with PHP curl call

Hello: I am trying to do an API call using curl_init; 您好:我正在尝试使用curl_init进行API调用; have made some good progress but seem to be stuck... 取得了一些良好的进步,但似乎陷于困境...

we have an interface (swagger) that allows us to do the curl call and test it which works: here is the curl commands from that: 我们有一个接口(swagger),允许我们执行curl调用并测试它是否有效:这是来自curl的命令:

curl -X POST --header "Content-Type: application/x-www-form-urlencoded" 
--header "Accept: application/json" 
--header "Authorization: Bearer xxxxx-xxxxxx- xxxxx-xxxxxxx" 
-d "username=xxxxxxxx39%40gmail.com&password=xxxx1234"        "http://xxxxxxxxx-xx-xx-201-115.compute-1.amazonaws.com:xxxx/api/users" 

here is my attempt to do the same call in PHP code: 这是我尝试在PHP代码中进行相同的调用:

$json = '{
"username": "xmanxxxxxx%40gmail.com",
"password": "xxxx1234"
}';


  $gtoken='xxxxxx-xxxxxx-xxx-xxxxxxxx';

$token_string="Authorization: Bearer ".$gtoken;


$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://exx-ccc-vvv-vvvv.compute-1.amazonaws.com:xxxx/api/users', //URL to the API
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $json,
CURLOPT_HEADER => true, // Instead of the "-i" flag
CURLOPT_HTTPHEADER => array('Content-Type: application/x-www-form-urlencoded','Accept: application/json',$token_string) 

));

curl_setopt($curl,CURLOPT_RETURNTRANSFER,TRUE);

$resp = curl_exec($curl);
curl_close($curl); 

I am getting a response code "500" which makes me think that there is something wrong with my input. 我收到一个响应代码“ 500”,使我认为输入内容有问题。 So I am wondering if anyone can help with this... 所以我想知道是否有人可以帮助您...

In your command line code, you post a standard URL encoded data string using -d "username=xxxxxxxx39%40gmail.com&password=xxxx1234" but in PHP you are creating a JSON string and sending it as a single post field (not properly URL encoded). 在您的命令行代码中,您使用-d "username=xxxxxxxx39%40gmail.com&password=xxxx1234"发布标准的URL编码数据字符串,但是在PHP中,您正在创建JSON字符串并将其作为单个发布字段发送(URL编码不正确) )。

I think this is what you need: 我认为这是您需要的:

$data = array(
    'username' => 'xmanxxxxxx@gmail.com',
    'password' => 'xxxx1234',
);

$data = http_build_query($data); // convert array to urlencoded string

curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

As far as I can tell the rest of the code looks fine. 据我所知,其余代码看起来还不错。

Also, you don't explicitly need to set the Content-Type header, cURL will do this for you when you pass a string to CURLOPT_POSTFIELDS . 另外,您不需要显式设置Content-Type标头,当您将字符串传递给CURLOPT_POSTFIELDS时,cURL会为您执行此操作。 It will set it to multipart/form-data if you pass an array to CURLOPT_POSTFIELDS . 如果将数组传递给CURLOPT_POSTFIELDS ,它将设置为multipart/form-data But having it doesn't hurt anything either. 但是拥有它也没有任何伤害。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM