Requests and Responses
There are two ways to perform HTTP requests with the related PEAR components: HTTP_Request and HTTP_Client. The latter composes the former to add capabilities such as handling redirects and persisting headers, cookie data, and request parameters across multiple requests. Here’s how to perform a simple request and extract response information when using HTTP_Request directly. <?php require_once 'HTTP/Request.php'; $request =& HTTP_Request('http://localhost.example'); $request->setMethod(HTTP_REQUEST_METHOD_GET); $request->setURL('http://localhost.example'); $response = $request->sendRequest(); ?>
Issues that cause errors include environmental requirements of the component not being met or the target of the request exceeding the redirect limit. PEAR: :isError is used to determine if the sendRequest call resulted in an error. If the request is sent successfully, several methods of the request object are available to extract response information. <?php if (!PEAR::isError($response)) { $code = $request->getResponseCode(); $reason = $request->getResponseReason(); $body = $request->getResponseBody(); $cookies = $request->getResponseCookies(); $headers = $request->getResponseHeader(); $contentType = $request->getResponseHeader('Content-Type'); } ?> Here are a few specifics about the response information methods.
sendRequest does not modify any parameters set by you that are specific to the request (as opposed to the response). That is, request instances can be reused and individual parameters modified only as needed to change what differs between consecutive requests. To “start fresh” with an existing request instance, simply explicitly call its constructor method. <?php $request =& new HTTP_Request; // ... $request->HTTP_Request(); // all parameters previously set will be cleared ?> © PEAR::HTTP_Client — Web Scraping >>> Back to TABLE OF CONTENTS <<< | |
Views: 428 | |
Total comments: 0 | |