Jar*_*ish 3 php rest curl jira
我正在尝试使用REST API和PHP/cURL更新一些自定义字段.
我想知道我是否可能在没有意识到的情况下编辑了一些东西,而我昨天所做的"工作"(我认为),它现在不起作用.
我使用不同的"方法"获得不同的响应,来自:
我使用POST方法得到这个,因为它在下面没有注释.
HTTP 405 - 请求的资源()不允许使用指定的HTTP方法.
如果我使用注释掉的PUT方法,我会得到这个,并注释掉POST.
{"status-code":500,"message":"Read timed out"}
Run Code Online (Sandbox Code Playgroud)而这一个混合和匹配PUT和POST.
{"errorMessages":["No content to map to Object due to end of input"]}
Run Code Online (Sandbox Code Playgroud)我错过了什么/做错了什么?我使用以下代码:
<?php
$username = 'username';
$password = 'password';
$url = "https://example.com/rest/api/2/issue/PROJ-827";
$ch = curl_init();
$headers = array(
'Accept: application/json',
'Content-Type: application/json'
);
$test = "This is the content of the custom field.";
$data = <<<JSON
{
"fields": {
"customfield_11334" : ["$test"]
}
}
JSON;
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// Also tried, with the above two lines commented out...
// curl_setopt($ch, CURLOPT_PUT, 1);
// curl_setopt($ch, CURLOPT_INFILE, $data);
// curl_setopt($ch, CURLOPT_INFILESIZE, strlen($data));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
$result = curl_exec($ch);
$ch_error = curl_error($ch);
if ($ch_error) {
echo "cURL Error: $ch_error";
} else {
echo $result;
}
curl_close($ch);
?>
Run Code Online (Sandbox Code Playgroud)
这里的问题是PHP的cURL API不是特别直观.
您可能认为因为使用以下选项发送POST请求主体,PUT请求将以相同的方式完成:
// works for sending a POST request
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// DOES NOT work to send a PUT request
curl_setopt($ch, CURLOPT_PUT, 1);
curl_setopt($ch, CURLOPT_PUTFIELDS, $data);
Run Code Online (Sandbox Code Playgroud)
相反,要发送PUT请求(带有关联的正文数据),您需要以下内容:
// The correct way to send a PUT request
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
Run Code Online (Sandbox Code Playgroud)
请注意,即使您发送PUT请求,仍然必须使用该CURLOPT_POSTFIELDS
选项发送您的PUT请求正文.这是一个令人困惑和不一致的过程,但如果您想使用PHP cURL绑定,那就是您所拥有的.
根据相关的手册输入文档,该CURLOPT_PUT
选项似乎只适用于直接输入文件:
对于HTTP PUT文件为TRUE.必须使用CURLOPT_INFILE和CURLOPT_INFILESIZE设置要PUT的文件.
更好的选择IMHO是使用自定义流包装器进行HTTP客户端操作.这带来了额外的好处,即不使您的应用程序依赖于底层的libcurl库.但是,这样的实现超出了这个问题的范围.如果您对开发流包装解决方案感兴趣,Google就是您的朋友.
归档时间: |
|
查看次数: |
5180 次 |
最近记录: |