【问题标题】:PHP catch failed to open stream: HTTP request failed! HTTP/1.1 401 UnauthorizedPHP catch 无法打开流:HTTP 请求失败! HTTP/1.1 401 未经授权
【发布时间】:2012-09-10 11:32:29
【问题描述】:

我正在尝试执行以下操作。

当我尝试使用 oAuth 访问服务时,如果我收到错误,因为我使用了错误的密钥,我不想显示错误消息,而是将用户发送到身份验证页面。

但是使用 try catch fn 不起作用。

这是我的代码:

$url = 'https://api.soundcloud.com/me.json?'.http_build_query(array(
        'oauth_token' => $token,
    ));
    //
    try{
        $user = json_decode(file_get_contents($url));
        return array(
            'uid' => $user->id,
            'nickname' => $user->username,
            'name' => $user->full_name,
            'location' => $user->country.' ,'.$user->country,
            'description' => $user->description,
            'image' => $user->avatar_url,
            'urls' => array(
                'MySpace' => $user->myspace_name,
                'Website' => $user->website,
            ),
        );
    }
    catch(Services_Soundcloud_Invalid_Http_Response_Code_Exception $e)
    {
        log_message('error', 'EXCEPTION: '.$e);
        return FALSE;
    }

我希望它返回用户数组或 FALSE。

有什么想法吗?

【问题讨论】:

  • 你尝试块很可能不会抛出那个又长又丑的异常。由于您只捕获该特定异常,因此任何其他异常都会继续进行。
  • 如果你改为catch (Exception $e) 是否有效?
  • 现在似乎正在使用 Exception $e,我之前尝试过,但运气不佳。也许它被缓存或什么的。无论如何,谢谢,您可以将其发布为答案吗?

标签: php oauth error-handling oauth-2.0


【解决方案1】:

您可以在这里查看捕获 file_get_content 错误

How can I handle the warning of file_get_contents() function in PHP?

这提供了不同的解决方案,例如查看响应标头

$content = @file_get_contents("http://www.google.com");
if (strpos($http_response_header[0], "200")) { 
   echo "SUCCESS";
} else { 
   echo "FAILED";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-21
    • 1970-01-01
    • 1970-01-01
    • 2020-01-21
    • 2023-01-01
    • 1970-01-01
    • 2015-11-21
    • 2021-05-04
    相关资源
    最近更新 更多