【问题标题】:How can I prevent Guzzle 3 from URLEncoding an Operation Parameter?如何防止 Guzzle 3 对操作参数进行 URLEncoding?
【发布时间】:2015-05-03 03:19:37
【问题描述】:

我正在使用 Guzzle 3 来处理超媒体 HTTP API,并且在使用 URL 路径作为参数时遇到了一些问题。该服务将返回 URL 路径以访问资源,并且除了参数化的路径正在被 URLEncoded 之外,大部分都在工作。

这是服务描述中的操作示例

"getWidget": {
  "uri": "{path}",
  "summary": "Get Widget",
  "httpMethod": "GET",
  "responseType": "class",
  "responseClass": "Service\\Responses\\Widget",
  "parameters": {
    "path": {
      "location": "uri"
    }
  }
}

我正在执行操作:

$client = WidgetClient::factory(array('base_url' => 'example.com'));

$args = array('path' => '/widget/abc123');
$command = $client->getCommand('getWidget', $args);
$result = $command->execute();

执行客户端请求时:http://example.com/%2Fwidget%2Fabc123 而不是http://example.com/widgetabc123

我已将参数处理追溯到UriTemplate::expandMatch(),它执行对参数进行编码的rawurlencode($variable) 调用——但我看不到避免编码的明确方法。

那么,使用 Guzzle 3 及其服务描述,如何在不进行 URLEncoded 的情况下将 URL 路径作为参数传递?

【问题讨论】:

    标签: php url uri guzzle


    【解决方案1】:

    作为临时解决方法(我希望有更好的方法),我订阅了client.create_request 事件并修改了路径以删除编码。这是初始版本,它会在最终版本之前进行清理:

    public function onClientCreateRequest(Event $event)
    {
        /** @var Request $request */
        $request = $event['request'];
        if (empty($request)) {
            return;
        }
    
        $url = $request->getUrl(true);
        if (empty($url)) {
            return;
        }
    
        $path = $url->getPath();
        $path = rawurldecode($path);
        $path = str_replace('//', '/', $path); 
    
        //$url->setPath($path);
        $request->setPath($path);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-21
      • 2017-10-04
      • 2010-09-14
      • 1970-01-01
      • 2016-12-31
      • 2014-04-18
      • 1970-01-01
      • 2015-05-22
      相关资源
      最近更新 更多