cURL PHP RESTful服务总是返回FALSE [英] cURL PHP RESTful service always returning FALSE

查看:164
本文介绍了cURL PHP RESTful服务总是返回FALSE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一些困难将json对象发送到使用REST的API。我是新的使用cURL,但我已经搜索了所有尝试找到我的问题的答案,但出现了短。我的cURL请求总是返回false。我知道它甚至没有发布我的json对象,因为我仍然会得到一个来自url的响应。我的代码如下。

I am having some difficulties POSTing a json object to an API that uses REST. I am new to using cURL, but I have searched all over to try to find an answer to my problem but have come up short. My cURL request is always returning false. I know it isn't even posting my json object because I would still get a response from the url. My code is below.

<?php

//API KEY = APIUsername
//API_CODE = APIPassword
$API_Key = "some API key";
$API_Code = "some API code";
$API_email = "email@email.com";
$API_password = "ohhello";
$url = "http://someURL.com/rest.svc/blah";


$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, $url);
header('Content-type: application/json');
$authData = "{\"APIUsername\":\"$API_Key\",\"APIPassword\":\"$API_Code\",\"EmailAddress\":\"$API_email\",\"Password\":\"$API_password\"}";
curl_setopt($ch, CURLOPT_POSTFIELDS, $authData);

//make the request
$result = curl_exec($ch);
$response = json_encode($result);
echo $response;

curl_close() 
?>

$ response只返回false

The $response returns just "false"

任何想法?

推荐答案

$ response code> curl_exec()返回false(即,失败)到 $ result 。回显 curl_error($ ch)(在调用curl_exec之后)看到cURL错误,如果是问题。

$response is likely false because curl_exec() returns false (i.e., failure) into $result. Echo out curl_error($ch) (after the call to curl_exec) to see the cURL error, if that's the problem.

另一方面,我认为您的CURLOPT_POSTFIELDS格式无效。

On a different note, I think your CURLOPT_POSTFIELDS is in an invalid format. You don't pass a JSON string to that.


此参数可以作为
a传递urlencoded string like
'para1 = val1& para2 = val2& ...'或作为
数组,字段名称为键,
字段数据为值。

This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value.

- curl_setopt()的PHP文档






更新

错误是添加此选项:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

您会收到SSL验证错误,因为与浏览器不同,cURL没有预装的受信任证书列表权限(CA),因此默认情况下不会信任SSL证书。快速解决方案是只接受证书,而不通过使用上面的行验证。更好的解决方案是手动添加您想要接受的证书或CA。请参见此有关cURL和SSL的文章了解更多信息。

You get an SSL verification error because cURL, unlike browsers, does not have a preloaded list of trusted certificate authorities (CAs), so no SSL certificates are trusted by default. The quick solution is to just accept certificates without verification by using the line above. The better solution is to manually add only the certificate(s) or CA(s) you want to accept. See this article on cURL and SSL for more information.

这篇关于cURL PHP RESTful服务总是返回FALSE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆