PHP cURL POST返回415 - 不支持的媒体类型

时间:2012-06-18 17:22:38

标签: php post curl jboss

我有一个简单的PHP脚本,它通过cURL发送HTTP POST请求,并期望响应一个json字符串(本来喜欢使用像pecl_http / HTTPRequest这样的现有库,但是可以' T)。调用始终失败,出现415错误 - 不支持的媒体类型。我认为我没有正确配置cURL,但经过多次搜索,我无法找出我做错的事情。这是一些代码:

class URLRequest
{
    public $url;
    public $headers;
    public $params;
    public $body;
    public $expectedFormat;
    public $method;

    public function URLRequest($aUrl, array $aHeaders, array $aParams, $aFormat = "json", $isPost = false, $aBody = "+")
    {
        $this->url = $aUrl;
        $this->headers = $aHeaders;
        $this->params = $aParams;
        $this->expectedFormat = $aFormat;
        $this->method = ($isPost ? "POST" : "GET");
        $this->body = $aBody;

    }

    public function exec()
    {

        $queryStr = "?";
        foreach($this->params as $key=>$val)
            $queryStr .= $key . "=" . $val . "&";

        //trim the last '&'
        $queryStr = rtrim($queryStr, "&");

        $url = $this->url . $queryStr;

        $request = curl_init();
        curl_setopt($request, CURLOPT_URL, $url);
        curl_setopt($request, CURLOPT_HEADER, 1);
        curl_setopt($request, CURLOPT_HTTPHEADER, $this->headers);
        curl_setopt($request, CURLOPT_RETURNTRANSFER, 1);
        //curl_setopt($request, CURLOPT_SSL_VERIFYPEER, false);

        if($this->method == "POST")
        {
            curl_setopt($request, CURLOPT_POST, 1);
            curl_setopt($request, CURLOPT_POSTFIELDS, $this->body);

            //this prevents an additions code 100 from getting returned
            //found it in some forum - seems kind of hacky
            curl_setopt($request, CURLOPT_HTTPHEADER, array("Expect:"));
        }

        $response = curl_exec($request);
        curl_close($request);

        preg_match("%(?<=HTTP/[0-9]\.[0-9] )[0-9]+%", $response, $code);

        $resp = "";
        if($this->expectedFormat == "json")
        {
            //parse response
        }
        elseif($this->expectedFormat == "xml")
        {
            //parse response
        }

        return $resp;

    }
}


$url = "http://mydomain.com/myrestcall";

$query = array( "arg_1" =>      "test001",
                "arg_2" =>      "test002",
                "arg_3" =>      "test003");

$headers = array(    "Accept-Encoding" =>    "gzip",
                    "Content-Type" =>       "application/json",
                    "Accept" =>             "application/json",
                    "custom_header_1" =>    "test011",
                    "custom_header_2" =>    "test012",
                    "custom_header_3" =>    "test013");

$body = array(  "body_arg_1" =>      "test021",
                "body_arg_2" =>     array("test022", "test023"), 
                "body_arg_3" =>     "test024"); 


$request = new URLRequest($url, $headers, $query, "json", true, $body);

$response = $request->exec();

......和回复:

HTTP/1.1 415 Unsupported Media Type
Server: Apache-Coyote/1.1
X-Powered-By: Servlet 2.5; JBoss-5.0/JBossWeb-2.1
Content-Type: text/html;charset=utf-8
Content-Length: 1047
Date: Mon, 18 Jun 2012 16:30:44 GMT

<html><head><title>JBoss Web/2.1.3.GA - Error report</title></head><body><h1>HTTP Status 415 - </h1><p><b>type</b> Status report</p><p><b>message</b> <u></u></p><p><b>description</b> <u>The server refused this request because the request entity is in a format not supported by the requested resource for the requested method ().</u></p><h3>JBoss Web/2.1.3.GA</h3></body></html>

任何见解或想法?

提前致谢!

4 个答案:

答案 0 :(得分:13)

问题解决了!这是问题所在:

发送一个关联数组的标题不适用于cURL。有几个论坛分散在展示示例中,使用关联数组作为标题。不要做!

正确的方式(它也散布在互联网周围,但我太密集而不能注意到)是将标题键/值对构造为字符串,并传递一个标准数组设置CURLOPT_HTTPHEADER选项时的这些字符串。

总而言之,

<强> WRONG:

$headers = array(    "Accept-Encoding" =>    "gzip",
                     "Content-Type" =>       "application/json",
                     "custom_header_1" =>    "test011",
                     "custom_header_2" =>    "test012",
                     "custom_header_3" =>    "test013");

从右:

$headers = array(    "Accept-Encoding: gzip",
                     "Content-Type: application/json",
                     "custom_header_1: test011",
                     "custom_header_2: test012",
                     "custom_header_3: test013");

我希望在他们浪费尽可能多的时间进行调试之前,这会让其他一些高尚的东西派上用场。

如果我不得不猜测,我会假设同样的规则也适用于POST正文键/值对,这就是为什么@ drew010关于使用http_build_query()json_encode()的评论字符串化你的信息正文也是一个好主意。

感谢大家的非常有用的评论,感谢您的时间和考虑。最后,http流量的并排比较(通过Wireshark捕获)揭示了这个问题。

谢谢!

答案 1 :(得分:8)

我认为问题在于您将数组作为CURLOPT_POSTFIELDS选项传递。通过传递数组,当服务器可能期望POST时,这会强制multipart/form-data请求使用application/x-www-form-urlencoded

尝试更改

curl_setopt($request, CURLOPT_POSTFIELDS, $this->body);

curl_setopt($request, CURLOPT_POSTFIELDS, http_build_query($this->body));

有关详细信息,请参阅http_build_query以及此答案:My cURL request confuses some servers?

答案 2 :(得分:1)

我遇到了同样的问题,并修复了更改标题的问题。

我的代码:

$authorization = 'authorization: Bearer '.trim($apiKey);
$header = [
'Content-Type: application/json',
$authorization
];
curl_setopt($session, CURLOPT_HTTPHEADER, $header);

我不知道为什么数组函数不起作用:

curl_setopt($session, CURLOPT_HTTPHEADER, array('Content-Type: 
application/json',
$authorization));

答案 3 :(得分:1)

这对我有用

 $data ="data";

 $headers = [
                "Content-Type: application/json",
                "X-Content-Type-Options:nosniff",
                "Accept:application/json",
                "Cache-Control:no-cache"
            ];

  $auth =  $USER . ":" . $PASSWORD;


 $curl = curl_init();
        curl_setopt($curl,CURLOPT_URL, $url);
        curl_setopt($curl,CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl,CURLOPT_ENCODING, "");
        curl_setopt($curl,CURLOPT_MAXREDIRS, 10);
        curl_setopt($curl,CURLOPT_TIMEOUT, 0);
        curl_setopt($curl,CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);
        curl_setopt($curl,CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($curl,CURLOPT_POSTFIELDS, json_encode($data)); 
        curl_setopt($curl, CURLOPT_USERPWD,  $auth);  
        curl_setopt($curl,CURLOPT_HTTPHEADER, $headers);

         $result = curl_exec($curl);