• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

PHP HTTPClient类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了PHP中HTTPClient的典型用法代码示例。如果您正苦于以下问题:PHP HTTPClient类的具体用法?PHP HTTPClient怎么用?PHP HTTPClient使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了HTTPClient类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的PHP代码示例。

示例1: post

 /**
  * Sign and post the given Atom entry as a Salmon message.
  *
  * Side effects: may generate a keypair on-demand for the given user,
  * which can be very slow on some systems.
  *
  * @param string $endpoint_uri
  * @param string $xml string representation of payload
  * @param Profile $actor local user profile whose keys to sign with
  * @return boolean success
  */
 public function post($endpoint_uri, $xml, $actor)
 {
     if (empty($endpoint_uri)) {
         return false;
     }
     foreach ($this->formatClasses() as $class) {
         try {
             $envelope = $this->createMagicEnv($xml, $actor, $class);
         } catch (Exception $e) {
             common_log(LOG_ERR, "Salmon unable to sign: " . $e->getMessage());
             return false;
         }
         $headers = array('Content-Type: application/magic-envelope+xml');
         try {
             $client = new HTTPClient();
             $client->setBody($envelope);
             $response = $client->post($endpoint_uri, $headers);
         } catch (HTTP_Request2_Exception $e) {
             common_log(LOG_ERR, "Salmon ({$class}) post to {$endpoint_uri} failed: " . $e->getMessage());
             continue;
         }
         if ($response->getStatus() != 200) {
             common_log(LOG_ERR, "Salmon ({$class}) at {$endpoint_uri} returned status " . $response->getStatus() . ': ' . $response->getBody());
             continue;
         }
         // Success!
         return true;
     }
     return false;
 }
开发者ID:Grasia,项目名称:bolotweet,代码行数:41,代码来源:salmon.php


示例2: handle_start

 function handle_start(&$event, $param)
 {
     if (!isset($_FILES['imageshack_file'])) {
         return;
     }
     if ($_FILES['imageshack_file']['error'] || !is_uploaded_file($_FILES['imageshack_file']['tmp_name'])) {
         msg(sprintf('The was a problem receiving the file from you (error %d)', $_FILES['imageshack_file']['error']), -1);
         return;
     }
     require_once DOKU_INC . '/inc/HTTPClient.php';
     $http = new HTTPClient();
     $http->timeout = 60;
     $http->headers['Content-Type'] = 'multipart/form-data';
     $data = array('xml' => 'yes', 'fileupload' => array('filename' => $_FILES['imageshack_file']['name'], 'mimetype' => $_FILES['imageshack_file']['type'], 'body' => file_get_contents($_FILES['imageshack_file']['tmp_name'])));
     $xml = $http->post('http://imageshack.us/index.php', $data);
     if (!$xml) {
         msg('There was a problem with uploading your file to imageshack: ' . $http->error, -1);
         return;
     }
     $xml = new SimpleXMLElement($xml);
     if (!$xml) {
         msg('ImageShack did not accept your upload', -1);
         return;
     }
     list($w, $h) = explode('x', (string) $xml->resolution[0]);
     $_SESSION['imageshack'][] = array('link' => (string) $xml->image_link[0], 'adlink' => (string) $xml->ad_link[0], 'name' => (string) $xml->image_name[0], 'width' => $w, 'height' => $h, 'size' => (string) $xml->filesize[0]);
 }
开发者ID:splitbrain,项目名称:dokuwiki-plugin-imageshack,代码行数:27,代码来源:action.php


示例3: httpClient

 /**
  * Set up an HTTPClient with auth for our resource.
  *
  * @param string $method
  * @return HTTPClient
  */
 private function httpClient($method = 'GET')
 {
     $client = new HTTPClient($this->url);
     $client->setMethod($method);
     $client->setAuth($this->user, $this->pass);
     return $client;
 }
开发者ID:microcosmx,项目名称:experiments,代码行数:13,代码来源:atompub_test.php


示例4: onStartNoticeSave

 function onStartNoticeSave($notice)
 {
     $args = $this->testArgs($notice);
     common_debug("Blogspamnet args = " . print_r($args, TRUE));
     $requestBody = xmlrpc_encode_request('testComment', array($args));
     $request = new HTTPClient($this->baseUrl, HTTPClient::METHOD_POST);
     $request->setHeader('Content-Type', 'text/xml');
     $request->setBody($requestBody);
     $httpResponse = $request->send();
     $response = xmlrpc_decode($httpResponse->getBody());
     if (xmlrpc_is_fault($response)) {
         throw new ServerException("{$response['faultString']} ({$response['faultCode']})", 500);
     } else {
         common_debug("Blogspamnet results = " . $response);
         if (preg_match('/^ERROR(:(.*))?$/', $response, $match)) {
             throw new ServerException(sprintf(_("Error from %s: %s"), $this->baseUrl, $match[2]), 500);
         } else {
             if (preg_match('/^SPAM(:(.*))?$/', $response, $match)) {
                 throw new ClientException(sprintf(_("Spam checker results: %s"), $match[2]), 400);
             } else {
                 if (preg_match('/^OK$/', $response)) {
                     // don't do anything
                 } else {
                     throw new ServerException(sprintf(_("Unexpected response from %s: %s"), $this->baseUrl, $response), 500);
                 }
             }
         }
     }
     return true;
 }
开发者ID:microcosmx,项目名称:experiments,代码行数:30,代码来源:BlogspamNetPlugin.php


示例5: extract_posts

 function extract_posts($arg_url)
 {
     $httpclient = new HTTPClient();
     $json_data = $httpclient->send($arg_url, 'get');
     if (empty($json_data)) {
         $this->message = 'Empty content returned';
         return false;
     }
     // convert json to php array
     $array_data = json_decode($json_data, true);
     // get data
     $facebook_posts = $array_data['data'];
     if (count($facebook_posts) > 0) {
         foreach ($facebook_posts as $facebook_post) {
             $post_content = $facebook_post['message'];
             $post_title = $facebook_post['name'];
             $post_author = $this->author_id;
             $post_status = $this->status_id;
             $post_date_gmt = gmdate('Y-m-d H:i:s', strtotime($facebook_post['created_time']));
             $post_date = get_date_from_gmt($post_date_gmt);
             $facebook_id = $facebook_post['id'];
             // build the post array
             $this->posts[] = compact('post_content', 'post_title', 'post_author', 'post_status', 'post_date', 'post_date_gmt', 'facebook_id');
         }
         // end of foreach
     }
     // end of if
     return true;
 }
开发者ID:EricYue2012,项目名称:FacebookPostsImporter,代码行数:29,代码来源:Importer.php


示例6: testNET_HTTP_HTTPClient

 function testNET_HTTP_HTTPClient()
 {
     $robot = new HTTPClient();
     // connect to url
     $res = $robot->Fetch("http://webta.net");
     $this->assertTrue($res, "Can't fetch url");
     /* end of tests */
 }
开发者ID:jasherai,项目名称:libwebta,代码行数:8,代码来源:tests.php


示例7: testPostRequestIsUnsuccessful

 function testPostRequestIsUnsuccessful()
 {
     \VCR\VCR::insertCassette('gathercontent_post_projects_failure.yml');
     $subject = new HTTPClient('[email protected]', 'bogus-api-key');
     $response = $subject->post('https://api.gathercontent.com/projects', ['account_id' => '20225', 'name' => 'Project Name'], ['Accept: application/vnd.gathercontent.v0.5+json']);
     $this->assertNotEquals(200, $response->status);
     $this->assertEquals('Invalid credentials.', $response->body);
 }
开发者ID:vigetlabs,项目名称:gather-content-api,代码行数:8,代码来源:HTTPClientTest.php


示例8: checkUpdates

 public function checkUpdates(FeedSub $feedsub)
 {
     $request = new HTTPClient();
     $feed = $request->get($feedsub->uri);
     if (!$feed->isOk()) {
         throw new ServerException('FeedSub could not fetch id=' . $feedsub->id . ' (Error ' . $feed->getStatus() . ': ' . $feed->getBody());
     }
     $feedsub->receive($feed->getBody(), null);
 }
开发者ID:bashrc,项目名称:gnusocial-debian,代码行数:9,代码来源:feedpoll.php


示例9: fromHcardUrl

 static function fromHcardUrl($url)
 {
     $client = new HTTPClient();
     $client->setHeader('Accept', 'text/html,application/xhtml+xml');
     $response = $client->get($url);
     if (!$response->isOk()) {
         return null;
     }
     return self::hcardHints($response->getBody(), $response->getUrl());
 }
开发者ID:Br3nda,项目名称:StatusNet,代码行数:10,代码来源:discoveryhints.php


示例10: load_page

 function load_page($URL, $ispost = false, $postparams = "")
 {
     //echo "LOAAAAAAAAAAAAADING $URL<br /><br />";
     $return = false;
     $snoopy = new HTTPClient();
     if ($snoopy->loadPage($URL)) {
         $return = $snoopy->getData();
     }
     unset($snoopy);
     return $return;
 }
开发者ID:keithdsouza,项目名称:twitlookup,代码行数:11,代码来源:class.Util.php


示例11: testData_XML_RSS_RSSReader

 function testData_XML_RSS_RSSReader()
 {
     $http = new HTTPClient();
     // rss 2.0
     $url = 'http://aggressiva.livejournal.com/data/rss';
     $http->SetTimeouts(30, 15);
     $xml = $http->Fetch($url);
     $Reader = new RSSReader();
     $Reader->Parse($xml);
     $data = $Reader->GetData();
     $this->assertTrue($data['channel'], "No channel found");
     $this->assertTrue($data['item']['pubdate'], "No items found");
 }
开发者ID:rchicoria,项目名称:epp-drs,代码行数:13,代码来源:tests.php


示例12: updateProfileURL

 /**
  * Look up and if necessary create an Ostatus_profile for the remote entity
  * with the given profile page URL. This should never return null -- you
  * will either get an object or an exception will be thrown.
  *
  * @param string $profile_url
  * @return Ostatus_profile
  * @throws Exception on various error conditions
  * @throws OStatusShadowException if this reference would obscure a local user/group
  */
 public static function updateProfileURL($profile_url, $hints = array())
 {
     $oprofile = null;
     $hints['profileurl'] = $profile_url;
     // Fetch the URL
     // XXX: HTTP caching
     $client = new HTTPClient();
     $client->setHeader('Accept', 'text/html,application/xhtml+xml');
     $response = $client->get($profile_url);
     if (!$response->isOk()) {
         // TRANS: Exception. %s is a profile URL.
         throw new Exception(sprintf(_('Could not reach profile page %s.'), $profile_url));
     }
     // Check if we have a non-canonical URL
     $finalUrl = $response->getUrl();
     if ($finalUrl != $profile_url) {
         $hints['profileurl'] = $finalUrl;
     }
     // Try to get some hCard data
     $body = $response->getBody();
     $hcardHints = DiscoveryHints::hcardHints($body, $finalUrl);
     if (!empty($hcardHints)) {
         $hints = array_merge($hints, $hcardHints);
     }
     // Check if they've got an LRDD header
     $lrdd = LinkHeader::getLink($response, 'lrdd', 'application/xrd+xml');
     try {
         $xrd = new XML_XRD();
         $xrd->loadFile($lrdd);
         $xrdHints = DiscoveryHints::fromXRD($xrd);
         $hints = array_merge($hints, $xrdHints);
     } catch (Exception $e) {
         // No hints available from XRD
     }
     // If discovery found a feedurl (probably from LRDD), use it.
     if (array_key_exists('feedurl', $hints)) {
         return self::ensureFeedURL($hints['feedurl'], $hints);
     }
     // Get the feed URL from HTML
     $discover = new FeedDiscovery();
     $feedurl = $discover->discoverFromHTML($finalUrl, $body);
     if (!empty($feedurl)) {
         $hints['feedurl'] = $feedurl;
         return self::ensureFeedURL($feedurl, $hints);
     }
     // TRANS: Exception. %s is a URL.
     throw new Exception(sprintf(_m('Could not find a feed URL for profile page %s.'), $finalUrl));
 }
开发者ID:bashrc,项目名称:gnusocial-debian,代码行数:58,代码来源:update_ostatus_profiles.php


示例13: onStartShowSections

 function onStartShowSections($action)
 {
     $name = $action->trimmed('action');
     if ($name == 'tag') {
         $taginput = $action->trimmed('tag');
         $tag = common_canonical_tag($taginput);
         if (!empty($tag)) {
             $url = sprintf('http://hashtags.wikia.com/index.php?title=%s&action=render', urlencode($tag));
             $editurl = sprintf('http://hashtags.wikia.com/index.php?title=%s&action=edit', urlencode($tag));
             $request = HTTPClient::start();
             $response = $request->get($url);
             $html = $response->getBody();
             $action->elementStart('div', array('id' => 'wikihashtags', 'class' => 'section'));
             if ($response->isOk() && !empty($html)) {
                 $action->element('style', null, "span.editsection { display: none }\n" . "table.toc { display: none }");
                 $action->raw($html);
                 $action->elementStart('p');
                 $action->element('a', array('href' => $editurl, 'title' => sprintf(_m('Edit the article for #%s on WikiHashtags'), $tag)), _m('Edit'));
                 $action->element('a', array('href' => 'http://www.gnu.org/copyleft/fdl.html', 'title' => _m('Shared under the terms of the GNU Free Documentation License'), 'rel' => 'license'), _m('GNU FDL'));
                 $action->elementEnd('p');
             } else {
                 $action->element('a', array('href' => $editurl), sprintf(_m('Start the article for #%s on WikiHashtags'), $tag));
             }
             $action->elementEnd('div');
         }
     }
     return true;
 }
开发者ID:Grasia,项目名称:bolotweet,代码行数:28,代码来源:WikiHashtagsPlugin.php


示例14: linkback_get_target

function linkback_get_target($target)
{
    // Resolve target (https://github.com/converspace/webmention/issues/43)
    $request = HTTPClient::start();
    try {
        $response = $request->head($target);
    } catch (Exception $ex) {
        return NULL;
    }
    try {
        $notice = Notice::fromUri($response->getEffectiveUrl());
    } catch (UnknownUriException $ex) {
        preg_match('/\\/notice\\/(\\d+)(?:#.*)?$/', $response->getEffectiveUrl(), $match);
        $notice = Notice::getKV('id', $match[1]);
    }
    if ($notice instanceof Notice && $notice->isLocal()) {
        return $notice;
    } else {
        $user = User::getKV('uri', $response->getEffectiveUrl());
        if (!$user) {
            preg_match('/\\/user\\/(\\d+)(?:#.*)?$/', $response->getEffectiveUrl(), $match);
            $user = User::getKV('id', $match[1]);
        }
        if (!$user) {
            preg_match('/\\/([^\\/\\?#]+)(?:#.*)?$/', $response->getEffectiveUrl(), $match);
            if (linkback_lenient_target_match(common_profile_url($match[1]), $response->getEffectiveUrl())) {
                $user = User::getKV('nickname', $match[1]);
            }
        }
        if ($user instanceof User) {
            return $user;
        }
    }
    return NULL;
}
开发者ID:bashrc,项目名称:gnusocial-debian,代码行数:35,代码来源:util.php


示例15: getTweetHtml

function getTweetHtml($url)
{
    try {
        $client = new HTTPClient();
        $response = $client->get($url);
    } catch (HTTP_Request2_Exception $e) {
        print "ERROR: HTTP response " . $e->getMessage() . "\n";
        return false;
    }
    if (!$response->isOk()) {
        print "ERROR: HTTP response " . $response->getCode() . "\n";
        return false;
    }
    $body = $response->getBody();
    return tweetHtmlFromBody($body);
}
开发者ID:microcosmx,项目名称:experiments,代码行数:16,代码来源:importtwitteratom.php


示例16: httpRequest

function httpRequest($endpoint, $poststr)
{
    $request = HTTPClient::start();
    $request->setConfig(array('follow_redirects' => true, 'connect_timeout' => 120, 'timeout' => 120, 'ssl_verify_peer' => false, 'ssl_verify_host' => false));
    // Turn signed request query string back into an array
    parse_str($poststr, $postdata);
    return $request->post($endpoint, null, $postdata);
}
开发者ID:microcosmx,项目名称:experiments,代码行数:8,代码来源:oauth_post_notice.php


示例17: fetchUrl

 protected function fetchUrl($url, $method = HTTPClient::METHOD_GET)
 {
     $client = new HTTPClient();
     // GAAHHH, this method sucks! How about we make a better HTTPClient interface?
     switch ($method) {
         case HTTPClient::METHOD_GET:
             $response = $client->get($url);
             break;
         case HTTPClient::METHOD_HEAD:
             $response = $client->head($url);
             break;
         default:
             throw new Exception('Bad HTTP method.');
     }
     if ($response->getStatus() != 200) {
         throw new Exception('Unexpected HTTP status code.');
     }
     return $response;
 }
开发者ID:bashrc,项目名称:gnusocial-debian,代码行数:19,代码来源:lrddmethod.php


示例18: ping_broadcast_notice

function ping_broadcast_notice($notice)
{
    if ($notice->is_local != Notice::LOCAL_PUBLIC && $notice->is_local != Notice::LOCAL_NONPUBLIC) {
        return true;
    }
    # Array of servers, URL => type
    $notify = common_config('ping', 'notify');
    $profile = $notice->getProfile();
    $tags = ping_notice_tags($notice);
    foreach ($notify as $notify_url => $type) {
        switch ($type) {
            case 'xmlrpc':
            case 'extended':
                $req = xmlrpc_encode_request('weblogUpdates.ping', array($profile->nickname, common_local_url('showstream', array('nickname' => $profile->nickname)), common_local_url('shownotice', array('notice' => $notice->id)), common_local_url('userrss', array('nickname' => $profile->nickname)), $tags));
                $request = HTTPClient::start();
                $request->setConfig('connect_timeout', common_config('ping', 'timeout'));
                $request->setConfig('timeout', common_config('ping', 'timeout'));
                try {
                    $httpResponse = $request->post($notify_url, array('Content-Type: text/xml'), $req);
                } catch (Exception $e) {
                    common_log(LOG_ERR, "Exception pinging {$notify_url}: " . $e->getMessage());
                    continue;
                }
                if (!$httpResponse || mb_strlen($httpResponse->getBody()) == 0) {
                    common_log(LOG_WARNING, "XML-RPC empty results for ping ({$notify_url}, {$notice->id}) ");
                    continue;
                }
                $response = xmlrpc_decode($httpResponse->getBody());
                if (is_array($response) && xmlrpc_is_fault($response)) {
                    common_log(LOG_WARNING, "XML-RPC error for ping ({$notify_url}, {$notice->id}) " . "{$response['faultString']} ({$response['faultCode']})");
                } else {
                    common_log(LOG_INFO, "Ping success for {$notify_url} {$notice->id}");
                }
                break;
            case 'get':
            case 'post':
                $args = array('name' => $profile->nickname, 'url' => common_local_url('showstream', array('nickname' => $profile->nickname)), 'changesURL' => common_local_url('userrss', array('nickname' => $profile->nickname)));
                $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
                if ($type === 'get') {
                    $result = $fetcher->get($notify_url . '?' . http_build_query($args), array('User-Agent: StatusNet/' . STATUSNET_VERSION));
                } else {
                    $result = $fetcher->post($notify_url, http_build_query($args), array('User-Agent: StatusNet/' . STATUSNET_VERSION));
                }
                if ($result->status != '200') {
                    common_log(LOG_WARNING, "Ping error for '{$notify_url}' ({$notice->id}): " . "{$result->body}");
                } else {
                    common_log(LOG_INFO, "Ping success for '{$notify_url}' ({$notice->id}): " . "'{$result->body}'");
                }
                break;
            default:
                common_log(LOG_WARNING, 'Unknown notify type for ' . $notify_url . ': ' . $type);
        }
    }
    return true;
}
开发者ID:Br3nda,项目名称:StatusNet,代码行数:55,代码来源:ping.php


示例19: onCreateFileImageThumbnailSource

 public function onCreateFileImageThumbnailSource(File $file, &$imgPath, $media = null)
 {
     // If we are on a private node, we won't do any remote calls (just as a precaution until
     // we can configure this from config.php for the private nodes)
     if (common_config('site', 'private')) {
         return true;
     }
     if ($media !== 'image') {
         return true;
     }
     // If there is a local filename, it is either a local file already or has already been downloaded.
     if (!empty($file->filename)) {
         return true;
     }
     $this->checkWhitelist($file->getUrl());
     // First we download the file to memory and test whether it's actually an image file
     $imgData = HTTPClient::quickGet($file->getUrl());
     common_debug(sprintf('Downloading remote file id==%u with URL: %s', $file->id, $file->getUrl()));
     $info = @getimagesizefromstring($imgData);
     if ($info === false) {
         throw new UnsupportedMediaException(_('Remote file format was not identified as an image.'), $file->getUrl());
     } elseif (!$info[0] || !$info[1]) {
         throw new UnsupportedMediaException(_('Image file had impossible geometry (0 width or height)'));
     }
     $filehash = hash(File::FILEHASH_ALG, $imgData);
     try {
         // Exception will be thrown before $file is set to anything, so old $file value will be kept
         $file = File::getByHash($filehash);
         //FIXME: Add some code so we don't have to store duplicate File rows for same hash files.
     } catch (NoResultException $e) {
         $filename = $filehash . '.' . common_supported_mime_to_ext($info['mime']);
         $fullpath = File::path($filename);
         // Write the file to disk if it doesn't exist yet. Throw Exception on failure.
         if (!file_exists($fullpath) && file_put_contents($fullpath, $imgData) === false) {
             throw new ServerException(_('Could not write downloaded file to disk.'));
         }
         // Updated our database for the file record
         $orig = clone $file;
         $file->filehash = $filehash;
         $file->filename = $filename;
         $file->width = $info[0];
         // array indexes documented on php.net:
         $file->height = $info[1];
         // https://php.net/manual/en/function.getimagesize.php
         // Throws exception on failure.
         $file->updateWithKeys($orig, 'id');
     }
     // Get rid of the file from memory
     unset($imgData);
     $imgPath = $file->getPath();
     return false;
 }
开发者ID:bashrc,项目名称:gnusocial-debian,代码行数:52,代码来源:StoreRemoteMediaPlugin.php


示例20: doSpotifyLookup

function doSpotifyLookup($uri, $isArtist)
{
    $request = HTTPClient::start();
    $response = $request->get('http://ws.spotify.com/lookup/1/?uri=' . $uri);
    if ($response->isOk()) {
        $xml = simplexml_load_string($response->getBody());
        if ($isArtist) {
            return $xml->name;
        } else {
            return $xml->artist->name . ' - ' . $xml->name;
        }
    }
}
开发者ID:Grasia,项目名称:bolotweet,代码行数:13,代码来源:SpotifyPlugin.php



注:本文中的HTTPClient类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
PHP HTTPRequest类代码示例发布时间:2022-05-23
下一篇:
PHP HTTP类代码示例发布时间:2022-05-23
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap