当我在浏览器中访问这个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=ℑhttps://www.google.com/images/srpr/logo3w.png
编辑:我也尝试使用用户代理,但无济于事。
使用curl,它可以简单地在您的php中禁用url_fopen
它还使您可以完全控制更改user-agent
使用以下代码:
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");
错误的请求通常意味着您提供的参数之一是错误的。我总是做的是通过从我的web浏览器发送请求来测试API。我测试URL并检查结果