- 浏览: 408021 次
- 性别:
- 来自: 深圳
文章分类
最新评论
-
wcjagta:
...
dedecms插件开发教程 -
xc2013:
看起来不错 先下载来试试
ECSHOP完全静态化解决方法 -
greemranqq:
你好,我在xp 上做实验,也是JS css带不过来,关于 ro ...
nginx资源定向 css js路径问题 -
hotsmile:
表结构给出来吧,测试的提示说要注册,
中国移动CMPP短信开发平台通讯包 2.8 -
mengdejun:
gang80306176 写道这个插件怎么用和安装普通插件一样 ...
phpcms2008 sp4单网页编辑器插件
<?php /* Version 0.9, 6th April 2003 - Simon Willison ( http://simon.incutio.com/ ) Manual: http://scripts.incutio.com/httpclient/ */ class HttpClient { // Request vars var $host; var $port; var $path; var $method; var $postdata = ''; var $cookies = array(); var $referer; var $accept = 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,image/jpeg,image/gif,*/*'; var $accept_encoding = 'gzip'; var $accept_language = 'en-us'; var $user_agent = 'Incutio HttpClient v0.9'; // Options var $timeout = 20; var $use_gzip = true; var $persist_cookies = true; // If true, received cookies are placed in the $this->cookies array ready for the next request // Note: This currently ignores the cookie path (and time) completely. Time is not important, // but path could possibly lead to security problems. var $persist_referers = true; // For each request, sends path of last request as referer var $debug = false; var $handle_redirects = true; // Auaomtically redirect if Location or URI header is found var $max_redirects = 5; var $headers_only = false; // If true, stops receiving once headers have been read. // Basic authorization variables var $username; var $password; // Response vars var $status; var $headers = array(); var $content = ''; var $errormsg; // Tracker variables var $redirect_count = 0; var $cookie_host = ''; function HttpClient($host, $port=80) { $this->host = $host; $this->port = $port; } function get($path, $data = false) { $this->path = $path; $this->method = 'GET'; if ($data) { $this->path .= '?'.$this->buildQueryString($data); } return $this->doRequest(); } function post($path, $data) { $this->path = $path; $this->method = 'POST'; $this->postdata = $this->buildQueryString($data); return $this->doRequest(); } function buildQueryString($data) { $querystring = ''; if (is_array($data)) { // Change data in to postable data foreach ($data as $key => $val) { if (is_array($val)) { foreach ($val as $val2) { $querystring .= urlencode($key).'='.urlencode($val2).'&'; } } else { $querystring .= urlencode($key).'='.urlencode($val).'&'; } } $querystring = substr($querystring, 0, -1); // Eliminate unnecessary & } else { $querystring = $data; } return $querystring; } function doRequest() { // Performs the actual HTTP request, returning true or false depending on outcome if (!$fp = @fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout)) { // Set error message switch($errno) { case -3: $this->errormsg = 'Socket creation failed (-3)'; case -4: $this->errormsg = 'DNS lookup failure (-4)'; case -5: $this->errormsg = 'Connection refused or timed out (-5)'; default: $this->errormsg = 'Connection failed ('.$errno.')'; $this->errormsg .= ' '.$errstr; $this->debug($this->errormsg); } return false; } socket_set_timeout($fp, $this->timeout); $request = $this->buildRequest(); $this->debug('Request', $request); fwrite($fp, $request); // Reset all the variables that should not persist between requests $this->headers = array(); $this->content = ''; $this->errormsg = ''; // Set a couple of flags $inHeaders = true; $atStart = true; // Now start reading back the response while (!feof($fp)) { $line = fgets($fp, 4096); if ($atStart) { // Deal with first line of returned data $atStart = false; if (!preg_match('/HTTP\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/', $line, $m)) { $this->errormsg = "Status code line invalid: ".htmlentities($line); $this->debug($this->errormsg); return false; } $http_version = $m[1]; // not used $this->status = $m[2]; $status_string = $m[3]; // not used $this->debug(trim($line)); continue; } if ($inHeaders) { if (trim($line) == '') { $inHeaders = false; $this->debug('Received Headers', $this->headers); if ($this->headers_only) { break; // Skip the rest of the input } continue; } if (!preg_match('/([^:]+):\\s*(.*)/', $line, $m)) { // Skip to the next header continue; } $key = strtolower(trim($m[1])); $val = trim($m[2]); // Deal with the possibility of multiple headers of same name if (isset($this->headers[$key])) { if (is_array($this->headers[$key])) { $this->headers[$key][] = $val; } else { $this->headers[$key] = array($this->headers[$key], $val); } } else { $this->headers[$key] = $val; } continue; } // We're not in the headers, so append the line to the contents $this->content .= $line; } fclose($fp); // If data is compressed, uncompress it if (isset($this->headers['content-encoding']) && $this->headers['content-encoding'] == 'gzip') { $this->debug('Content is gzip encoded, unzipping it'); $this->content = substr($this->content, 10); // See http://www.php.net/manual/en/function.gzencode.php $this->content = gzinflate($this->content); } // If $persist_cookies, deal with any cookies if ($this->persist_cookies && isset($this->headers['set-cookie']) && $this->host == $this->cookie_host) { $cookies = $this->headers['set-cookie']; if (!is_array($cookies)) { $cookies = array($cookies); } foreach ($cookies as $cookie) { if (preg_match('/([^=]+)=([^;]+);/', $cookie, $m)) { $this->cookies[$m[1]] = $m[2]; } } // Record domain of cookies for security reasons $this->cookie_host = $this->host; } // If $persist_referers, set the referer ready for the next request if ($this->persist_referers) { $this->debug('Persisting referer: '.$this->getRequestURL()); $this->referer = $this->getRequestURL(); } // Finally, if handle_redirects and a redirect is sent, do that if ($this->handle_redirects) { if (++$this->redirect_count >= $this->max_redirects) { $this->errormsg = 'Number of redirects exceeded maximum ('.$this->max_redirects.')'; $this->debug($this->errormsg); $this->redirect_count = 0; return false; } $location = isset($this->headers['location']) ? $this->headers['location'] : ''; $uri = isset($this->headers['uri']) ? $this->headers['uri'] : ''; if ($location || $uri) { $url = parse_url($location.$uri); // This will FAIL if redirect is to a different site return $this->get($url['path']); } } return true; } function buildRequest() { $headers = array(); $headers[] = "{$this->method} {$this->path} HTTP/1.0"; // Using 1.1 leads to all manner of problems, such as "chunked" encoding $headers[] = "Host: {$this->host}"; $headers[] = "User-Agent: {$this->user_agent}"; $headers[] = "Accept: {$this->accept}"; if ($this->use_gzip) { $headers[] = "Accept-encoding: {$this->accept_encoding}"; } $headers[] = "Accept-language: {$this->accept_language}"; if ($this->referer) { $headers[] = "Referer: {$this->referer}"; } // Cookies if ($this->cookies) { $cookie = 'Cookie: '; foreach ($this->cookies as $key => $value) { $cookie .= "$key=$value; "; } $headers[] = $cookie; } // Basic authentication if ($this->username && $this->password) { $headers[] = 'Authorization: BASIC '.base64_encode($this->username.':'.$this->password); } // If this is a POST, set the content type and length if ($this->postdata) { $headers[] = 'Content-Type: application/x-www-form-urlencoded'; $headers[] = 'Content-Length: '.strlen($this->postdata); } $request = implode("\r\n", $headers)."\r\n\r\n".$this->postdata; return $request; } function getStatus() { return $this->status; } function getContent() { return $this->content; } function getHeaders() { return $this->headers; } function getHeader($header) { $header = strtolower($header); if (isset($this->headers[$header])) { return $this->headers[$header]; } else { return false; } } function getError() { return $this->errormsg; } function getCookies() { return $this->cookies; } function getRequestURL() { $url = 'http://'.$this->host; if ($this->port != 80) { $url .= ':'.$this->port; } $url .= $this->path; return $url; } // Setter methods function setUserAgent($string) { $this->user_agent = $string; } function setAuthorization($username, $password) { $this->username = $username; $this->password = $password; } function setCookies($array) { $this->cookies = $array; } // Option setting methods function useGzip($boolean) { $this->use_gzip = $boolean; } function setPersistCookies($boolean) { $this->persist_cookies = $boolean; } function setPersistReferers($boolean) { $this->persist_referers = $boolean; } function setHandleRedirects($boolean) { $this->handle_redirects = $boolean; } function setMaxRedirects($num) { $this->max_redirects = $num; } function setHeadersOnly($boolean) { $this->headers_only = $boolean; } function setDebug($boolean) { $this->debug = $boolean; } // "Quick" static methods function quickGet($url) { $bits = parse_url($url); $host = $bits['host']; $port = isset($bits['port']) ? $bits['port'] : 80; $path = isset($bits['path']) ? $bits['path'] : '/'; if (isset($bits['query'])) { $path .= '?'.$bits['query']; } $client = new HttpClient($host, $port); if (!$client->get($path)) { return false; } else { return $client->getContent(); } } function quickPost($url, $data) { $bits = parse_url($url); $host = $bits['host']; $port = isset($bits['port']) ? $bits['port'] : 80; $path = isset($bits['path']) ? $bits['path'] : '/'; $client = new HttpClient($host, $port); if (!$client->post($path, $data)) { return false; } else { return $client->getContent(); } } function debug($msg, $object = false) { if ($this->debug) { print '<div style="border: 1px solid red; padding: 0.5em; margin: 0.5em;"><strong>HttpClient Debug:</strong> '.$msg; if ($object) { ob_start(); print_r($object); $content = htmlentities(ob_get_contents()); ob_end_clean(); print '<pre>'.$content.'</pre>'; } print '</div>'; } } } ?>
HttpClient Manual
HttpClient Home | Download HttpClient (tar.gz) | HttpClient Examples | HttpClient Demo
Only methods that are intended to be called from outside the script are described. For details of internal methods, Use The Source :)
HttpClient($host, $port = 80)
bool get($path, $data = false)
getError()
method. bool post($path, $data)
getError()
method. string getContent()
string getStatus()
array getHeaders()
string getHeader($header)
string getError()
string getRequestURL()
array getCookies()
string quickGet($url)
$pageContent = HttpClient::quickGet($url);
Returns the empty string on failure. string quickPost($url, $data)
$pageContent = HttpClient::quickPost($url, $data);
Returns the empty string on failure. See also post()
. void setUserAgent($string)
void setAuthorization($username, $password)
void setCookies($array)
void setUseGzip($boolean)
void setPersistCookies($boolean)
void setPersistReferers($boolean)
void setHandleRedirects($boolean)
void setMaxRedirects($int)
void setHeadersOnly($boolean)
void setDebug($boolean)
void debug($message, $object = false)
Grabbing an HTML page (static method)
$pageContents = HttpClient::quickGet('http://example.com/');
Posting a form and grabbing the response (static method)
$pageContents = HttpClient::quickPost('http://example.com/someForm', array(
'name' => 'Some Name',
'email' => 'email@example.com'
));
The static methods are easy to use, but seriously limit the functionality of the class as you cannot access returned headers or use facilities such as cookies or authentication.
A simple GET request using the class
$client = new HttpClient('example.com');
if (!$client->get('/')) {
die('An error occurred: '.$client->getError());
}
$pageContents = $client->getContent();
A GET request with debugging turned on
$client = new HttpClient('example.com');
$client->setDebug(true);
if (!$client->get('/')) {
die('An error occurred: '.$client->getError());
}
$pageContents = $client->getContent();
A GET request demonstrating automatic redirection
$client = new HttpClient('www.amazon.com');
$client->setDebug(true);
if (!$client->get('/')) {
die('An error occurred: '.$client->getError());
}
$pageContents = $client->getContent();
Check to see if a page exists
$client = new HttpClient('example.com');
$client->setDebug(true);
if (!$client->get('/thispagedoesnotexist')) {
die('An error occurred: '.$client->getError());
}
if ($client->getStatus() == '404') {
echo 'Page does not exist!';
}
$pageContents = $client->getContent();
Fake the User Agent string
$client = new HttpClient('example.com');
$client->setDebug(true);
$client->setUserAgent('Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.3a) Gecko/20021207');
if (!$client->get('/')) {
die('An error occurred: '.$client->getError());
}
$pageContents = $client->getContent();
Log in to a site via a login form, then request a page
In this example, it is assumed that correctly logging in will result in the server sending a sesssion cookie of some sort. This cookie is resent by the HttpClient class automatically, so a request to a page that requires users to be logged in will now work.
$client = new HttpClient('example.com');
$client->post('/login.php', array(
'username' => 'Simon',
'password' => 'ducks'
));
if (!$client->get('/private.php')) {
die('An error occurred: '.$client->getError());
}
$pageContents = $client->getContent();
Using HTTP authorisation
Note that the class uses the American spelling 'authorization' to fit with the HTTP specification.
$client = new HttpClient('example.com');
$client->setAuthorization('Username', 'Password');
if (!$client->get('/')) {
die('An error occurred: '.$client->getError());
}
$pageContents = $client->getContent();
Print out the headers from a response
$client = new HttpClient('example.com');
if (!$client->get('/')) {
die('An error occurred: '.$client->getError());
}
print_r($client->getHeaders());
Setting the maximum number of redirects
$client = new HttpClient('www.amazon.com');
$client->setDebug(true);
$client->setMaxRedirects(3);
$client->get('/');
官网:http://scripts.incutio.com/httpclient/
- HttpClient.tar.tar (3.6 KB)
- 下载次数: 10
发表评论
-
php异步操作类库
2011-06-05 16:01 1828httpclient for php 的选择常用方案有以 ... -
织梦HTTP IMAGE下载类
2011-06-05 14:57 1876<?php if(!defined('DEDEINC ... -
php汉字转拼音
2011-06-05 14:41 1610<?php /**************** ... -
PHP采集利器:Snoopy 试用心得
2011-06-05 14:34 14077Snoopy是一个php类,用 ... -
php异步调用 提高用户体验
2011-05-30 14:22 1319这是我的一个技术很好的朋友写的,要我发表在我的博客上可让php ... -
PHP 异步调用 后台调用 持续执行 断开连接/浏览器
2011-05-26 10:31 1718标题很怪,因为我也 ... -
php socket模拟POST GET请求 fsockopen版
2011-05-26 10:14 7389function httpRequestGET($url){ ... -
mantis
2011-05-25 09:50 1294mantis 缺陷管理平台Mantis,也做Mantis ... -
Curl参数一览
2011-05-06 17:30 1485* 目录 1. 介绍 ... -
PHPRPC
2011-04-24 11:01 1329PHPRPC 是一个轻型的、安全的、跨网际的、跨语言的、跨平台 ... -
PHP身份证验证程序
2011-04-24 10:56 1272<?php // 计算身份证校验码,根据国家标准GB 116 ... -
nginx 502 Bad Gateway 错误问题收集
2011-04-23 09:43 1790502是FastCGI出现问题,所以从FastCGI配置入手。 ... -
深入理解PHP内存管理之谁动了我的内存
2011-04-12 21:57 849首先让我们看一个问题: ... -
socket模拟post表单
2011-04-11 15:40 2808post的本质就是发送给目的程序一个标志为post的协议串如下 ... -
OAUTH协议
2011-04-09 09:59 1116OAUTH协议为用户资源的 ... -
nginx/windows: 让nginx以服务的方式运行
2011-04-09 09:33 1157在windows下安装了nginx, 郁闷是发现它没有以服 ... -
ThinkPHP处理海量数据分表机制详细代码
2011-04-07 18:27 7225应用ThinkPHP内置的分表算法处理百万级用户数据. ... -
php 分库分表hash算法
2011-04-07 18:16 1700//分库分表算法 function calc_hash_d ... -
nginx配置文件实例: php (fastcgi), perl, proxy, rrd, nagios
2011-04-06 20:33 1840nginx.conf worker_processes 5; ... -
Nginx location 指令的使用(中文翻译)
2011-04-06 20:31 1167location syntax: location [=|~ ...
相关推荐
本文将深入探讨基于Socket实现的HttpClient,以及它如何处理GET和POST协议。 首先,Socket是TCP/IP协议族中的一个概念,它提供了一种进程间通信(IPC)机制,允许两台计算机上的应用程序通过网络进行数据交换。在C...
GET和POST是HTTP请求的两种主要方法,GET用于获取资源,POST用于提交数据。 在描述中提到的"资源达人分享计划"可能是指一个社区或者项目,鼓励用户分享他们的编程资源,包括代码示例、教程等。这可能是此压缩包的...
HttpClient库广泛应用于需要与Web服务器进行交互的Java应用中,包括发送GET和POST请求等基本操作。 ### GET请求 GET请求是最常见的HTTP请求方法,用于从服务器获取资源。使用HttpClient发起GET请求的步骤如下: 1....
1. 创建HttpGet或HttpPost对象,指定目标URL。对于HTTPS,URL应以"https://"开头。 2. 如果需要发送数据,可以通过HttpEntity或NameValuePair设置请求体。 3. 使用HttpClientUtil创建的HttpClient实例执行请求,如`...
GET主要用于获取资源,而POST则常用于提交数据到服务器。HttpClient库提供了丰富的API来处理这两种请求类型,允许设置请求头、携带参数、处理响应等。例如,你可以使用`HttpGet`和`HttpPost`类创建请求对象,通过`...
在HttpClient 4.3之前的版本中,可以通过`setHeader`方法来添加自定义头部: ```java HttpGet httpGet = new HttpGet("http://example.com"); httpGet.setHeader("Custom-Header", "Custom-Value"); ...
HttpClient是一个灵活且强大的HTTP客户端API,它允许开发者执行各种HTTP方法(如GET、POST等),处理响应,以及管理连接池。要创建一个简单的HttpClient实例,你需要以下步骤: 1. 引入Apache HttpClient库: 在你...
GET请求 $ http = new HttpClient ();$ http -> set_header ( 'User-Agent' , 'Mozilla/5.0 (Windows NT 5.1; rv:13.0) Gecko/20100101 Firefox/13.0.1' ); $ http -> get ( 'http://www.example.com/' ); echo $ ...
在Java应用程序中,如果你需要与Web服务器进行交互,发送GET、POST或者其他HTTP方法的请求,HttpClient是一个非常理想的工具。 HttpClient 4.2.5是该库的一个稳定版本,它包含了多项改进和修复,以提高性能和稳定性...
HttpClient是一个强大的Java库,它允许开发者执行各种HTTP请求并处理响应,包括GET、POST、PUT、DELETE等HTTP方法。HttpClientUtils将HttpClient的功能进行了封装,使得在实际开发中,开发者可以更方便地进行网络...
创建HttpClient实例后,可以调用`execute()`方法发起GET、POST等不同类型的HTTP请求。例如: ```java HttpClient httpClient = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(...
HttpClient是Apache提供的一款强大的HTTP客户端库,支持多种HTTP协议版本和功能,包括GET、POST请求、Cookie管理、重定向处理等。在远程接口调用中,HttpClient允许我们构建自定义的请求并获取响应,非常适用于API...
这篇博客"Apache HttpClient Demo"可能详细介绍了如何使用这个库来发起HTTP请求,包括GET、POST以及其他HTTP方法。 在HttpClient中,首先需要创建一个HttpClient实例。这是基础的HTTP客户端,将负责发送请求并接收...
请求行格式为"方法 URL HTTP/版本",例如"GET /index.html HTTP/1.1"或"POST /submit HTTP/1.1"。首部字段可以设置如"Host"、"User-Agent"等,POST请求还需添加"Content-Type"和"Content-Length"字段。 3. **接收...
HttpClient不仅支持基本的HTTP方法(如GET、POST),还支持更高级的功能,如Cookie管理、重定向处理、身份验证、连接池管理等。 在了解HttpClient之前,我们首先要知道HTTP协议。HTTP(超文本传输协议)是一种应用...
4. **使用HttpClient进行HTTP请求**:现在,你可以在你的服务类或控制器类中注入`RestTemplate`,并使用它来发送GET、POST等HTTP请求。例如,发送一个GET请求: ```java @Autowired private RestTemplate ...
2. POST方法:POST方法用于向服务器提交数据,常用于表单提交或上传文件。请求体中可以携带大量数据,比GET更安全。在Wince的Socket编程中,我们需要构造带有POST请求头的完整HTTP报文,然后发送到服务器,最后接收...
在Java开发中,Apache HttpClient是一个强大的HTTP客户端库,常用于执行HTTP请求,如GET、POST、PUT和DELETE等。这个工具类是基于HttpClient 4.5.12版本进行封装,目的是简化HTTP操作并提供更便捷的使用方式。以下是...
- 发送请求并获取响应:使用HttpClient的`execute`方法发送请求,得到`HttpResponse`对象。 2. **处理响应**: - 获取响应状态码:通过`HttpResponse`的`getStatusLine`方法获取HTTP状态码,了解请求是否成功。 ...