2

我想使用 HTTP_Request2 Pear Class 发布。当我使用 cURL 做同样的事情时我是成功的,但是当我使用 HTTP_Request 时我没有得到响应数据。它说内容长度为 0。我阅读了 HTTP_Request2 的 PEAR 文档并按照它来编写代码。如果有人指出我的错误,那将有很大帮助。cURL 方法有效,但 HTTP_Request2 方法无效。我认为 HTTP_Request2 方法无法发布数据,但我也不确定标头。我的代码是

function header()
{
$this->setGuid(guid());
$this->header = array($this->service, 
time(), $this->getGuid());
return $this->header;
}

function header1()
{
$this->setGuid(guid());
$this->header = array('X-OpenSRF-service: '.$this->service, 
'X-OpenSRF-xid: '.time(), 'X-OpenSRF-thread: '.$this->getGuid());
return $this->header;
}
function toArray()
{
$url4 = urldata($this->method, $this->param);
return $url4; //returns an encoded url
}
function send1()
{
require_once 'HTTP/Request2.php';

//------cURL Method-------------------------
$endpoint = $this->endpoint;
$data = $this->toArray();
$header = $this->header1();
$url_post = 'http://'.$endpoint.'/osrf-http-translator';
$this->curl = curl_init();
curl_setopt($this->curl, CURLOPT_URL, $url_post);
curl_setopt($this->curl, CURLOPT_HEADER, 1);
curl_setopt($this->curl, CURLOPT_POST, 1);
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($this->curl, CURLOPT_HTTPHEADER, $header);
$this->server_result = curl_exec($this->curl);
if (curl_error($this->curl) != 0 ) {
$error = 'Curl error: ' . curl_error($this->curl);
return $error;
}
var_dump ($this->server_result);
echo "<HR />";   

//-----HTTP_REQUEST2 Method---------------       
$request = new HTTP_Request2();
$request->setUrl($url_post);
$request->setHeader(array('X-OpenSRF-service' => $header[0], 'X-OpenSRF-xid' => $header[1], 'X-OpenSRF-thread' => $header[2]));
$request->setMethod(HTTP_Request2::METHOD_POST);
$request->addPostParameter($data);
var_dump ($request); echo "<HR />";
$response = $request->send(); var_dump($response);
}
4

1 回答 1

0

HTTP_Request2::send()方法的结果与curl_exec. 它不是字符串,而是另一种类型,即HTTP_Request2_Response.

要将响应正文作为字符串检索(HTTP 响应包含标头和正文),请使用以下HTTP_Request2_Response::getBody方法:

...
$response = $request->send();
$responseBody = $response->getBody();

这应该做你正在寻找的,$responseBody然后是一个字符串。更笼统地说:HTTP_Request2具有面向对象的接口。这允许使用不同的适配器(例如 Curl 和套接字,或者您甚至可以编写自己的适配器,例如用于测试)以及以流式方式检索响应主体(例如,对于大型响应,您不会将所有响应都放入单个一次串)。

于 2012-09-17T18:26:36.303 回答