WP_REMOTE_POST代码转换

时间:2020-02-21 作者:Jared Sturgill

我正在尝试将此php代码转换为wordpress wp\\u remote\\u post()格式。想法,想法,这不是我的强项,哈哈。

<?php
require_once \'HTTP/Request2.php\';
$request = new HTTP_Request2();
$request->setUrl(\'https://xxxx.yyyyy.zzzzz\');
$request->setMethod(HTTP_Request2::METHOD_POST);
$request->setConfig(array(
  \'follow_redirects\' => TRUE
));
$request->setHeader(array(
  \'x-api-key\' => \'ppppppppppppppp\',
  \'Content-Type\' => \'application/json\'
));
$request->setBody(\'{\\n    "object_type": "Leaderboard",\\n    "action": "list",\\n    "pagination": {\\n       "limit": 5,\\n       "order": false\\n    },\\n    "data": {\\n        "username": "[email protected]"\\n    }\\n}\');
try {
  $response = $request->send();
  if ($response->getStatus() == 200) {
    echo $response->getBody();
  }
  else {
    echo \'Unexpected HTTP status: \' . $response->getStatus() . \' \' .
    $response->getReasonPhrase();
  }
}
catch(HTTP_Request2_Exception $e) {
  echo \'Error: \' . $e->getMessage();
}

1 个回复
SO网友:Dipendra Pancholi

Use this code :

$url = \'https://xxxx.yyyyy.zzzzz\';

$body_array = array(
                        \'object_type\' => \'Leaderboard\',
                        \'action\' => \'list\',
                        \'pagination\'    => array(
                                                \'limit\' => 5,
                                                \'order\' => false
                                            ),
                        \'data\'          => array(
                                                \'username\'  => \'[email protected]\'
                                            )
                    );



$response = wp_remote_post( $url, array(
        \'method\'      => \'POST\',
        \'timeout\'     => 45,
        \'redirection\' => 5,
        \'httpversion\' => \'1.0\',
        \'blocking\'    => true,
        \'headers\'     => array(
                            \'x-api-key\' => \'ppppppppppppppp\',
                            \'Content-Type\' => \'application/json\'
                        ),
        \'body\'        => json_encode( $body_array ),
        \'cookies\'     => array()
    )
);

if ( is_wp_error( $response ) ) {
    $error_message = $response->get_error_message();
    echo "Something went wrong: $error_message";
} else {
    echo \'Response:<pre>\';
    print_r( $response );
    echo \'</pre>\';
}

相关推荐