dooso0594 2017-03-10 12:12
浏览 52
已采纳

PHP> cURL>按顺序覆盖http方法>请求

I'm going crazy trying to figure out whats happening to an easy piece of code.

I'll write less code as I can to focus the issue.

Target

Execute two or more cURL requests with the same handle but different options.

cURL wrapper portion

public function __construct(){
    $this->handle = curl_init();
}

public function execute(){
    $handle = $this->handle;
    # ... some default, not relevant, options ... #
    # Retrieve the http method
    $http_method = $this->http_method;
    # Set the method
    switch($http_method){
        case 'GET':
            curl_setopt($handle, CURLOPT_HTTPGET, true);
            break;
        case 'POST':
            curl_setopt($handle, CURLOPT_POST, true);
            break;
        default:
            curl_setopt($handle, CURLOPT_CUSTOMREQUEST, $http_method);
            break;
    }
    # Set the url
    curl_setopt($handle, CURLOPT_URL, $this->url);
    # Retrieve the payload
    $payload = $this->payload;
    # Set the payload
    if(!empty($payload)){
        # Specify data to send
        curl_setopt($handle, CURLOPT_POSTFIELDS, $payload);
    }
    # Execute the request
    $result = curl_exec($handle);
    # Reset the handle
    curl_reset($handle);
    # Update the handle
    $this->handle = $handle;
}

Sample of use

    # First
    $obj->setHttpMethod('post');
    $obj->setURL("someurl");
    $payload = array(
        'field' => 'value'
    );
    $obj->setPayload($payload);
    $result = $obj->execute();

    # Second
    $obj->setHttpMethod('get');
    $obj->setURL("anotherurl");
    $result = $obj->execute();

Result

Second is executed as a POST instead of GET.

Conclusion

Thanks in advance: I will love any suggestion.

  • 写回答

1条回答 默认 最新

  • drsfgwuw61488 2017-03-10 15:01
    关注

    Just to post it as an answer:

    The post fields are already retained when you do a POST request, and subsequently do a GET request.

    Thus, changing the fields to null, would make cUrl do a GET request rather than POST.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条