HTTP请求失败!HTTP/1.1 400错误请求

5

我正在尝试在Jira中创建一个问题。

当我进行GET请求时,可以得到正确的响应,但是当我进行POST请求时出现了问题。以下是代码:

<?php

$userName ='xxxxxxxxxxxxxxxx';
$password ='xxxxxxxxxxxx';

$data = ['fields' => ['projects'=>['key'=>'ABC'],'summary'=>'abc','description'=>'abc','issuetype'=>['name'=>'Task']]];

$data = http_build_query($data);
$context = 
     array("http"=>
        array(
            "method" => "POST",
                "header" => "Authorization: Basic " . base64_encode($userName.':'.$password) . "\r\n".
                'Accept: application/json'."\r\n".
                "Content-Length: ".strlen($data)."\r\n".
                    'Content-Type: application/json'."\r\n",
            'content' => $data,
            'verify_peer'=>false,
            'verify_peer_name'=>false,
            )
            );
$context = stream_context_create($context);
$result = file_get_contents("https://xxxxx.atlassian.net/rest/api/2/issue/", false, $context);
echo "The result is ", $result;

我遇到了以下错误:

Warning:file_get_contents(https://xxxxx.atlassian.net/rest/api/2/issue/):
failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in
/var/www/html/test/new.php on line 27

有人能帮我吗?谢谢。

附言:

我不想使用curl代替http-streams,因为谷歌应用引擎不支持curl。


你正在发送一个查询字符串,但声称要发送JSON。这可能是你的第一个问题。 - Jason McCreary
@JasonMcCreary 这是使用curl的示例,链接为https://developer.atlassian.com/jiradev/api-reference/jira-rest-apis你能建议一下应该使用什么POST URL吗? - Vaibhav Desai
2个回答

8
http_build_query()生成一个url编码的字符串。然而,API需要JSON格式的数据。您应该使用json_encode()代替它。
$data = http_build_query($data);

To:

$data = json_encode($data);

虽然这可能不是您的唯一问题,但这绝对是导致400 Bad Request错误的一个问题。


谢谢Jason,你是对的,使用json_encode()解决了问题。 我还有一个小问题, $data=array('fields' => array ('project' => array ('key' => 'WOIS',),'summary' => 'ABC','description' => 'ABC','issuetype' => array ('name' => 'Task',),),);和 $data = ['fields' => ['projects'=>['key'=>'WOIS'],'summary'=>'adfsdf','description'=>'adfefsa','issuetype'=>['name'=>'Task']]];有什么区别呢? 因为如果我使用第二个$data,它无法识别project字段。在我看来,这两种表示都是正确的。 谢谢。 - Vaibhav Desai
好的。我建议您另外提一个问题,这样更清晰明了。欢迎来到StackOverflow。 - Jason McCreary

0

你的代码里可能有错别字吗?

$data=array('fields' => array ('project' => array ('key' => 'WOIS',),'summary' => 'ABC','description' => 'ABC','issuetype' => array ('name' => 'Task',),),); 

对比

$data = ['fields' => ['projects'=>['key'=>'WOIS'],'summary'=>'adfsdf','descriptio‌​n'=>'adfefsa','issue‌​type'=>['name'=>'Tas‌​k']]];

第一行写着project,而第二行写着projects


这个问题已经有一个被接受的答案了,而且问题不是因为打错字母导致的... - ᴄʀᴏᴢᴇᴛ

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接