2

每当我在浏览器中访问此 URL 时,它都可以正常工作,并且文件会上传到我的帐户:

http://api.imgur.com/2/upload.json?key=<my key>&image=<url to image>

但是当我尝试在 PHP 中使用类似的东西检索它时file_get_contents,我收到以下错误消息:

Warning: file_get_contents(<URL>): failed to open stream:
HTTP request failed! HTTP/1.1 400 Bad Request

您可以使用此 URL 查看示例:http ://api.imgur.com/2/upload.json?key=&image=https://www.google.com/images/srpr/logo3w.png

编辑:我也尝试使用用户代理,但无济于事。

4

2 回答 2

1

错误的请求主要意味着您提供的参数之一是错误的。我总是做的是通过从我的网络浏览器发送请求来测试 API。我测试 URL 并检查结果。

于 2013-01-05T02:31:35.007 回答
1

使用 curl,可能只是 url_fopen 在您的 php 中被禁用

它还使您可以完全控制更改用户代理

使用此代码:

function getContentWithCurl($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // Set so curl_exec returns the result instead of outputting it.
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_USERAGENT , ">>>PUT_USER_AGENT_HERE<<<" );
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
        curl_setopt($ch, CURLOPT_MAXREDIRS, 5);

        // Get the response and close the channel.
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }

getContentWithCurl("YOUR_URL_HERE");

于 2013-01-05T02:53:09.583 回答