What is curl.exe?
Содержание:
- MingW32
- Time Conditions
- curl_getinfo
- DESCRIPTION
- URL
- Метод POST
- TELNET
- Location header
- Building Windows DLLs and C run-time (CRT) linkage issues
- RETURN VALUE
- Команда curl
- HTTP OPTIONS
- NETWORK OPTIONS
- Multithreading notes
- Cross compile
- REDUCING SIZE
- PORTS
- PROGRESS METER
- Building libcurl.dll on Windows
- Использования cURL онлайн
- Forms explained
- Следовать за редиректами
- Using BSD-style lwIP instead of Winsock TCP/IP stack in Win32 builds
- Using BSD-style lwIP instead of Winsock TCP/IP stack in Win32 builds
- POST запрос при помощи cURL
MingW32
Make sure that MinGW32’s bin dir is in the search path, for example:
then run in the root dir. There are other make targets available to build libcurl with more features, use:
- to build with Zlib support;
- to build with SSL and Zlib enabled;
- to build with SSH2, SSL, Zlib;
- to build with SSH2, SSL, Zlib and SSPI support.
If you have any problems linking libraries or finding header files, be sure to verify that the provided files use the proper paths, and adjust as necessary. It is also possible to override these paths with environment variables, for example:
It is also possible to build with other LDAP SDKs than MS LDAP; currently it is possible to build with native Win32 OpenLDAP, or with the Novell CLDAP SDK. If you want to use these you need to set these vars:
or for using the Novell SDK:
If you want to enable LDAPS support then set LDAPS=1.
Time Conditions
HTTP allows a client to specify a time condition for the document it requests. It is or . curl allows you to specify them with the / flag.
For example, you can easily make a download that only gets performed if the remote file is newer than a local copy. It would be made like:
Or you can download a file only if the local file is newer than the remote one. Do this by prepending the date string with a , as in:
You can specify a «free text» date as condition. Tell curl to only download the file if it was updated since January 12, 2012:
Curl will then accept a wide range of date formats. You always make the date check the other way around by prepending it with a dash ().
curl_getinfo
curl_getinfo — получает информацию, касающуюся специфической передачи/transfer.
Описание
string curl_getinfo (resource ch, int opt)
-
CURLINFO_EFFECTIVE_URL — Последний
использованный URL -
CURLINFO_HTTP_CODE — Последний полученный код
HTTP -
CURLINFO_FILETIME — Дата модификации
загруженного документа, если она неизвестна, возвращается -1. -
CURLINFO_TOTAL_TIME — Полное время выполнения
операции в секундах. -
CURLINFO_NAMELOOKUP_TIME — Время разрешения
имени сервера в секундах. -
CURLINFO_CONNECT_TIME — Время, затраченное на
установку соединения, в секундах -
CURLINFO_PRETRANSFER_TIME — Время, прошедшее
от начала операции до готовности к фактической передаче данных, в
секундах -
CURLINFO_STARTTRANSFER_TIME — Время, прошедшее
от начала операции до момента передачи первого байта данных, в
секундах -
CURLINFO_REDIRECT_TIME — Общее время,
затраченное на перенапрвления, в секундах -
CURLINFO_SIZE_UPLOAD — Количество байт при
закачке -
CURLINFO_SIZE_DOWNLOAD — Количество байт при
загрузке -
CURLINFO_SPEED_DOWNLOAD — Средняя скорость
закачки -
CURLINFO_SPEED_UPLOAD — Средняя скорость
загрузки -
CURLINFO_HEADER_SIZE — Суммарный размер всех
полученных заголовков -
CURLINFO_REQUEST_SIZE — Суммарный размер всех
отправленных запросов, в настоящее время используется только для HTTP запросов -
CURLINFO_SSL_VERIFYRESULT — Результат
проверки SSL сертификата, запрошенной с помощью установки
параметра CURLOPT_SSL_VERIFYPEER -
CURLINFO_CONTENT_LENGTH_DOWNLOAD —
размер загруженного документа, прочитанный из заголовка
Content-Length -
CURLINFO_CONTENT_LENGTH_UPLOAD — Размер
закачиваемых данных -
CURLINFO_CONTENT_TYPE — Содержимое
полученного заголовка Content-type, или NULL в случае, когда этот
заголовок не был получен
При вызове без необязательного аргумента opt
возвращается ассоциативный массив со следующими индексами, которые
соответствуют значениям аргумента opt:
-
«url»
-
«content_type»
-
«http_code»
-
«header_size»
-
«request_size»
-
«filetime»
-
«ssl_verify_result»
-
«redirect_count»
-
«total_time»
-
«namelookup_time»
-
«connect_time»
-
«pretransfer_time»
-
«size_upload»
-
«size_download»
-
«speed_download»
-
«speed_upload»
-
«download_content_length»
-
«upload_content_length»
-
«starttransfer_time»
-
«redirect_time»
Пример использования curl_getinfo:
$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://www.example.com/"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLINFO_HEADER_OUT, true); // если этот параметр не указать не работает! curl_exec($ch); var_dump(curl_getinfo($ch,CURLINFO_HEADER_OUT));
Пример использования curl_getinfo:
$ch = curl_init(); // create cURL handle (ch) if (!$ch) { die("Couldn't initialize a cURL handle"); } // set some cURL options $ret = curl_setopt($ch, CURLOPT_URL, "http://mail.yahoo.com"); $ret = curl_setopt($ch, CURLOPT_HEADER, 1); $ret = curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); $ret = curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0); $ret = curl_setopt($ch, CURLOPT_TIMEOUT, 30); // execute $ret = curl_exec($ch); if (empty($ret)) { // some kind of an error happened die(curl_error($ch)); curl_close($ch); // close cURL handler } else { $info = curl_getinfo($ch); curl_close($ch); // close cURL handler if (empty($info)) { die("No HTTP code was returned"); } else { // load the HTTP codes $http_codes = parse_ini_file("path/to/the/ini/file/I/pasted/above"); // echo results echo "The server responded: <br />"; echo $info . " " . $http_codes]; } }
DESCRIPTION
curl is a tool for transfering data from or to a server. It supports these protocols: DICT, FILE, FTP, FTPS, GOPHER, GOPHERS, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, MQTT, POP3, POP3S, RTMP, RTMPS, RTSP, SCP, SFTP, SMB, SMBS, SMTP, SMTPS, TELNET or TFTP. The command is designed to work without user interaction.
curl offers a busload of useful tricks like proxy support, user authentication, FTP upload, HTTP post, SSL connections, cookies, file transfer resume and more. As you will see below, the number of features will make your head spin!
curl is powered by libcurl for all transfer-related features. See libcurl(3) for details.
URL
The URL syntax is protocol-dependent. You’ll find a detailed description in RFC 3986.
You can specify multiple URLs or parts of URLs by writing part sets within braces and quoting the URL as in:
«http://site.{one,two,three}.com»
or you can get sequences of alphanumeric series by using [] as in:
«ftp://ftp.example.com/file.txt»
«ftp://ftp.example.com/file.txt» (with leading zeros)
«ftp://ftp.example.com/file.txt»
Nested sequences are not supported, but you can use several ones next to each other:
«http://example.com/archive/vol/part{a,b,c}.html»
You can specify any amount of URLs on the command line. They will be fetched in a sequential manner in the specified order. You can specify command line options and URLs mixed and in any order on the command line.
You can specify a step counter for the ranges to get every Nth number or letter:
«http://example.com/file.txt»
«http://example.com/file.txt»
When using [] or {} sequences when invoked from a command line prompt, you probably have to put the full URL within double quotes to avoid the shell from interfering with it. This also goes for other characters treated special, like for example ‘&’, ‘?’ and ‘*’.
Provide the IPv6 zone index in the URL with an escaped percentage sign and the interface name. Like in
«http:///»
If you specify URL without protocol:// prefix, curl will attempt to guess what protocol you might want. It will then default to HTTP but try other protocols based on often-used host name prefixes. For example, for host names starting with «ftp.» curl will assume you want to speak FTP.
curl will do its best to use what you pass to it as a URL. It is not trying to validate it as a syntactically correct URL by any means but is instead very liberal with what it accepts.
curl will attempt to re-use connections for multiple file transfers, so that getting many files from the same server will not do multiple connects / handshakes. This improves speed. Of course this is only done on files specified on a single command line and cannot be used between separate curl invocations.
Метод POST
Метод GET приводит к тому, что вся введенная информация отображается в адресной строке браузера. Очевидно, что это не самый лучший способ в тех случаях, когда нужно отправить конфиденциальные данные или когда объем введенной информации очень велик. Для решения этой проблемы протокол HTTP предоставляет пользователю еще один метод — POST. С его помощью клиент отправляет данные отдельно от URL, и поэтому в адресной строке браузера вы их не увидите.
Форма, генерирующая POST-запрос, отличается от предыдущей лишь методом отправки:
<form method="POST" action="foo.cgi"> <input type=text name="year"> <input type=submit name=press value=" OK "> </form>
curl сформирует POST-запрос с теми же данными следующим образом:
$ curl -d "year=1990&press=%20OK%20" www.foo.com/foo.cgi
Обратите внимание на то, что данные, которые вы отправляете серверу, должны быть правильно закодированы. curl не сделает этого за вас
К примеру, если вы хотите, чтобы данные содержали пробел, то вам нужно заменить этот пробел на и т. п. Это одна из самых распространенных ошибок, в результате чего данные передаются не так, как нужно.
TELNET
The curl telnet support is basic and very easy to use. Curl passes all data passed to it on stdin to the remote server. Connect to a remote telnet server using a command line similar to:
And enter the data to pass to the server on stdin. The result will be sent to stdout or to the file you specify with .
You might want the / option to switch off the buffered output for slow connections or similar.
Pass options to the telnet protocol negotiation, by using the option. To tell the server we use a vt100 terminal, try something like:
Other interesting options for it include:
- Sets the X display location.
- Sets an environment variable.
NOTE: The telnet protocol does not specify any way to login with a specified user and password so curl can’t do that automatically. To do that, you need to track when the login prompt is received and send the username and password accordingly.
Location header
When a resource is requested from a server, the reply from the server may include a hint about where the browser should go next to find this page, or a new page keeping newly generated output. The header that tells the browser to redirect is .
Curl does not follow headers by default, but will simply display such pages in the same manner it displays all HTTP replies. It does however feature an option that will make it attempt to follow the pointers.
To tell curl to follow a Location:
If you use curl to POST to a site that immediately redirects you to another page, you can safely use () and / together. curl will only use POST in the first request, and then revert to GET in the following operations.
Building Windows DLLs and C run-time (CRT) linkage issues
As a general rule, building a DLL with static CRT linkage is highly
discouraged, and intermixing CRTs in the same app is something to avoid at
any cost.
Reading and comprehending Microsoft Knowledge Base articles KB94248 and
KB140584 is a must for any Windows developer. Especially important is full
understanding if you are not going to follow the advice given above.
If your app is misbehaving in some strange way, or it is suffering from
memory corruption, before asking for further help, please try first to
rebuild every single library your app uses as well as your app using the
debug multithreaded dynamic C runtime.
If you get linkage errors read section 5.7 of the FAQ document.
RETURN VALUE
(zero) means that the option was set properly, non-zero means an error occurred as <curl/curl.h> defines. See the libcurl-errors man page for the full list with descriptions.
Strings passed on to libcurl must be shorter than 8000000 bytes, otherwise curl_easy_setopt returns (added in 7.65.0).
is returned when the argument to an option is invalid, like perhaps out of range.
If you try to set an option that libcurl doesn’t know about, perhaps because the library is too old to support it or the option was removed in a recent version, this function will return . If support for the option was disabled at compile-time, it will return .
Команда curl
Перед тем как перейти к описанию того как может использоваться команда curl linux, давайте разберем саму утилиту и ее основные опции, которые нам понадобятся. Синтаксис утилиты очень прост:
$ curl опции ссылка
Теперь рассмотрим основные опции:
- -# — отображать простой прогресс-бар во время загрузки;
- -0 — использовать протокол http 1.0;
- -1 — использовать протокол шифрования tlsv1;
- -2 — использовать sslv2;
- -3 — использовать sslv3;
- -4 — использовать ipv4;
- -6 — использовать ipv6;
- -A — указать свой USER_AGENT;
- -b — сохранить Cookie в файл;
- -c — отправить Cookie на сервер из файла;
- -C — продолжить загрузку файла с места разрыва или указанного смещения;
- -m — максимальное время ожидания ответа от сервера;
- -d — отправить данные методом POST;
- -D — сохранить заголовки, возвращенные сервером в файл;
- -e — задать поле Referer-uri, указывает с какого сайта пришел пользователь;
- -E — использовать внешний сертификат SSL;
- -f — не выводить сообщения об ошибках;
- -F — отправить данные в виде формы;
- -G — если эта опция включена, то все данные, указанные в опции -d будут передаваться методом GET;
- -H — передать заголовки на сервер;
- -I — получать только HTTP заголовок, а все содержимое страницы игнорировать;
- -j — прочитать и отправить cookie из файла;
- -J — удалить заголовок из запроса;
- -L — принимать и обрабатывать перенаправления;
- -s — максимальное количество перенаправлений с помощью Location;
- -o — выводить контент страницы в файл;
- -O — сохранять контент в файл с именем страницы или файла на сервере;
- -p — использовать прокси;
- —proto — указать протокол, который нужно использовать;
- -R — сохранять время последнего изменения удаленного файла;
- -s — выводить минимум информации об ошибках;
- -S — выводить сообщения об ошибках;
- -T — загрузить файл на сервер;
- -v — максимально подробный вывод;
- -y — минимальная скорость загрузки;
- -Y — максимальная скорость загрузки;
- -z — скачать файл, только если он был модифицирован позже указанного времени;
- -V — вывести версию.
Это далеко не все параметры curl linux, но здесь перечислено все основное, что вам придется использовать.
HTTP OPTIONS
CURLOPT_AUTOREFERER
Automatically set Referer: header. See CURLOPT_AUTOREFERER
CURLOPT_ACCEPT_ENCODING
Accept-Encoding and automatic decompressing data. See CURLOPT_ACCEPT_ENCODING
CURLOPT_TRANSFER_ENCODING
Request Transfer-Encoding. See CURLOPT_TRANSFER_ENCODING
CURLOPT_FOLLOWLOCATION
Follow HTTP redirects. See CURLOPT_FOLLOWLOCATION
CURLOPT_UNRESTRICTED_AUTH
Do not restrict authentication to original host. CURLOPT_UNRESTRICTED_AUTH
CURLOPT_MAXREDIRS
Maximum number of redirects to follow. See CURLOPT_MAXREDIRS
CURLOPT_POSTREDIR
How to act on redirects after POST. See CURLOPT_POSTREDIR
CURLOPT_PUT
Issue an HTTP PUT request. See CURLOPT_PUT
CURLOPT_POST
Issue an HTTP POST request. See CURLOPT_POST
CURLOPT_POSTFIELDS
Send a POST with this data. See CURLOPT_POSTFIELDS
CURLOPT_POSTFIELDSIZE
The POST data is this big. See CURLOPT_POSTFIELDSIZE
CURLOPT_POSTFIELDSIZE_LARGE
The POST data is this big. See CURLOPT_POSTFIELDSIZE_LARGE
CURLOPT_COPYPOSTFIELDS
Send a POST with this data — and copy it. See CURLOPT_COPYPOSTFIELDS
CURLOPT_HTTPPOST
Multipart formpost HTTP POST. See CURLOPT_HTTPPOST
CURLOPT_REFERER
Referer: header. See CURLOPT_REFERER
CURLOPT_USERAGENT
User-Agent: header. See CURLOPT_USERAGENT
CURLOPT_HTTPHEADER
Custom HTTP headers. See CURLOPT_HTTPHEADER
CURLOPT_HEADEROPT
Control custom headers. See CURLOPT_HEADEROPT
CURLOPT_PROXYHEADER
Custom HTTP headers sent to proxy. See CURLOPT_PROXYHEADER
CURLOPT_HTTP200ALIASES
Alternative versions of 200 OK. See CURLOPT_HTTP200ALIASES
CURLOPT_COOKIE
Cookie(s) to send. See CURLOPT_COOKIE
CURLOPT_COOKIEFILE
File to read cookies from. See CURLOPT_COOKIEFILE
CURLOPT_COOKIEJAR
File to write cookies to. See CURLOPT_COOKIEJAR
CURLOPT_COOKIESESSION
Start a new cookie session. See CURLOPT_COOKIESESSION
CURLOPT_COOKIELIST
Add or control cookies. See CURLOPT_COOKIELIST
CURLOPT_ALTSVC
Specify the Alt-Svc: cache file name. See CURLOPT_ALTSVC
CURLOPT_ALTSVC_CTRL
Enable and configure Alt-Svc: treatment. See CURLOPT_ALTSVC_CTRL
CURLOPT_HSTS
Set HSTS cache file. See CURLOPT_HSTS
CURLOPT_HSTS_CTRL
Enable HSTS. See CURLOPT_HSTS_CTRL
CURLOPT_HSTSREADFUNCTION
Set HSTS read callback. See CURLOPT_HSTSREADFUNCTION
CURLOPT_HSTSREADDATA
Pass pointer to the HSTS read callback. See CURLOPT_HSTSREADDATA
CURLOPT_HSTSWRITEFUNCTION
Set HSTS write callback. See CURLOPT_HSTSWRITEFUNCTION
CURLOPT_HSTSWRITEDATA
Pass pointer to the HSTS write callback. See CURLOPT_HSTSWRITEDATA
CURLOPT_HTTPGET
Do an HTTP GET request. See CURLOPT_HTTPGET
CURLOPT_REQUEST_TARGET
Set the request target. CURLOPT_REQUEST_TARGET
CURLOPT_HTTP_VERSION
HTTP version to use. CURLOPT_HTTP_VERSION
CURLOPT_HTTP09_ALLOWED
Allow HTTP/0.9 responses. CURLOPT_HTTP09_ALLOWED
CURLOPT_IGNORE_CONTENT_LENGTH
Ignore Content-Length. See CURLOPT_IGNORE_CONTENT_LENGTH
CURLOPT_HTTP_CONTENT_DECODING
Disable Content decoding. See CURLOPT_HTTP_CONTENT_DECODING
CURLOPT_HTTP_TRANSFER_DECODING
Disable Transfer decoding. See CURLOPT_HTTP_TRANSFER_DECODING
CURLOPT_EXPECT_100_TIMEOUT_MS
100-continue timeout. See CURLOPT_EXPECT_100_TIMEOUT_MS
CURLOPT_TRAILERFUNCTION
Set callback for sending trailing headers. See CURLOPT_TRAILERFUNCTION
CURLOPT_TRAILERDATA
Custom pointer passed to the trailing headers callback. See CURLOPT_TRAILERDATA
CURLOPT_PIPEWAIT
Wait on connection to pipeline on it. See CURLOPT_PIPEWAIT
CURLOPT_STREAM_DEPENDS
This HTTP/2 stream depends on another. See CURLOPT_STREAM_DEPENDS
CURLOPT_STREAM_DEPENDS_E
This HTTP/2 stream depends on another exclusively. See CURLOPT_STREAM_DEPENDS_E
CURLOPT_STREAM_WEIGHT
Set this HTTP/2 stream’s weight. See CURLOPT_STREAM_WEIGHT
NETWORK OPTIONS
CURLOPT_URL
URL to work on. See CURLOPT_URL
CURLOPT_PATH_AS_IS
Disable squashing /../ and /./ sequences in the path. See CURLOPT_PATH_AS_IS
CURLOPT_PROTOCOLS
Allowed protocols. See CURLOPT_PROTOCOLS
CURLOPT_REDIR_PROTOCOLS
Protocols to allow redirects to. See CURLOPT_REDIR_PROTOCOLS
CURLOPT_DEFAULT_PROTOCOL
Default protocol. See CURLOPT_DEFAULT_PROTOCOL
CURLOPT_PROXY
Proxy to use. See CURLOPT_PROXY
CURLOPT_PRE_PROXY
Socks proxy to use. See CURLOPT_PRE_PROXY
CURLOPT_PROXYPORT
Proxy port to use. See CURLOPT_PROXYPORT
CURLOPT_PROXYTYPE
Proxy type. See CURLOPT_PROXYTYPE
CURLOPT_NOPROXY
Filter out hosts from proxy use. CURLOPT_NOPROXY
CURLOPT_HTTPPROXYTUNNEL
Tunnel through the HTTP proxy. CURLOPT_HTTPPROXYTUNNEL
CURLOPT_CONNECT_TO
Connect to a specific host and port. See CURLOPT_CONNECT_TO
CURLOPT_SOCKS5_AUTH
Socks5 authentication methods. See CURLOPT_SOCKS5_AUTH
CURLOPT_SOCKS5_GSSAPI_SERVICE
Socks5 GSSAPI service name. CURLOPT_SOCKS5_GSSAPI_SERVICE
CURLOPT_SOCKS5_GSSAPI_NEC
Socks5 GSSAPI NEC mode. See CURLOPT_SOCKS5_GSSAPI_NEC
CURLOPT_PROXY_SERVICE_NAME
Proxy authentication service name. CURLOPT_PROXY_SERVICE_NAME
CURLOPT_HAPROXYPROTOCOL
Send an HAProxy PROXY protocol v1 header. See CURLOPT_HAPROXYPROTOCOL
CURLOPT_SERVICE_NAME
Authentication service name. CURLOPT_SERVICE_NAME
CURLOPT_INTERFACE
Bind connection locally to this. See CURLOPT_INTERFACE
CURLOPT_LOCALPORT
Bind connection locally to this port. See CURLOPT_LOCALPORT
CURLOPT_LOCALPORTRANGE
Bind connection locally to port range. See CURLOPT_LOCALPORTRANGE
CURLOPT_DNS_CACHE_TIMEOUT
Timeout for DNS cache. See CURLOPT_DNS_CACHE_TIMEOUT
CURLOPT_DNS_USE_GLOBAL_CACHE
OBSOLETE Enable global DNS cache. See CURLOPT_DNS_USE_GLOBAL_CACHE
CURLOPT_DOH_URL
Use this DoH server for name resolves. See CURLOPT_DOH_URL
CURLOPT_BUFFERSIZE
Ask for alternate buffer size. See CURLOPT_BUFFERSIZE
CURLOPT_PORT
Port number to connect to. See CURLOPT_PORT
CURLOPT_TCP_FASTOPEN
Enable TFO, TCP Fast Open. See CURLOPT_TCP_FASTOPEN
CURLOPT_TCP_NODELAY
Disable the Nagle algorithm. See CURLOPT_TCP_NODELAY
CURLOPT_ADDRESS_SCOPE
IPv6 scope for local addresses. See CURLOPT_ADDRESS_SCOPE
CURLOPT_TCP_KEEPALIVE
Enable TCP keep-alive. See CURLOPT_TCP_KEEPALIVE
CURLOPT_TCP_KEEPIDLE
Idle time before sending keep-alive. See CURLOPT_TCP_KEEPIDLE
CURLOPT_TCP_KEEPINTVL
Interval between keep-alive probes. See CURLOPT_TCP_KEEPINTVL
CURLOPT_UNIX_SOCKET_PATH
Path to a Unix domain socket. See CURLOPT_UNIX_SOCKET_PATH
CURLOPT_ABSTRACT_UNIX_SOCKET
Path to an abstract Unix domain socket. See CURLOPT_ABSTRACT_UNIX_SOCKET
Multithreading notes
By default, jobs in IBM i won’t start with threading enabled. (Exceptions
include interactive PASE sessions started by or SSH.) If you use
curl in an environment without threading when options like async DNS were
enabled, you’ll messages like:
Don’t panic! curl and your program aren’t broken. You can fix this by:
- Set the environment variable to before starting
your program. This can be done at whatever scope you feel is appropriate. - Alternatively, start the job with the parameter set to .
Cross compile
Download and unpack the curl package.
to the new directory. (e.g. )
Set environment variables to point to the cross-compile toolchain and call
configure with any options you need. Be sure and specify the and
parameters at configuration time. The following script is an
example of cross-compiling for the IBM 405GP PowerPC processor using the
toolchain from MonteVista for Hardhat Linux.
#! /bin/sh export PATH=$PATH:/opt/hardhat/devkit/ppc/405/bin export CPPFLAGS="-I/opt/hardhat/devkit/ppc/405/target/usr/include" export AR=ppc_405-ar export AS=ppc_405-as export LD=ppc_405-ld export RANLIB=ppc_405-ranlib export CC=ppc_405-gcc export NM=ppc_405-nm ./configure --target=powerpc-hardhat-linux --host=powerpc-hardhat-linux --build=i586-pc-linux-gnu --prefix=/opt/hardhat/devkit/ppc/405/target/usr/local --exec-prefix=/usr/local
You may also need to provide a parameter like to
configure as it cannot detect the presence of a random number generating
device for a target system. The parameter specifies where curl
will be installed. If completes successfully, do and as usual.
In some cases, you may be able to simplify the above commands to as little as:
REDUCING SIZE
There are a number of configure options that can be used to reduce the size of
libcurl for embedded applications where binary size is an important factor.
First, be sure to set the variable when configuring with any relevant
compiler optimization flags to reduce the size of the binary. For gcc, this
would mean at minimum the -Os option, and potentially the ,
and options as well, e.g.
Note that newer compilers often produce smaller code than older versions
due to improved optimization.
Be sure to specify as many and flags on the
configure command-line as you can to disable all the libcurl features that you
know your application is not going to need. Besides specifying the
flags for all the types of URLs your application will not
use, here are some other flags that can reduce the size of the library:
- (disables support for the C-ARES DNS library)
- (disables support for HTTP cookies)
- (disables HTTP cryptographic authentication)
- (disables support for IPv6)
- (disables support for the built-in documentation)
- (disables support for HTTP and SOCKS proxies)
- (disables support for UNIX sockets)
- (eliminates debugging strings and error code strings)
- (disables support for versioned symbols)
- (eliminates unneeded symbols in the shared library)
- (disables support for the libidn DNS library)
- (disables support for RTMP)
- (disables support for SSL/TLS)
- (disables support for on-the-fly decompression)
The GNU compiler and linker have a number of options that can reduce the
size of the libcurl dynamic libraries on some platforms even further.
Specify them by providing appropriate and variables on
the configure command-line, e.g.
Be sure also to strip debugging symbols from your binaries after compiling
using ‘strip’ (or the appropriate variant if cross-compiling). If space is
really tight, you may be able to remove some unneeded sections of the shared
library using the -R option to objcopy (e.g. the .comment section).
Using these techniques it is possible to create a basic HTTP-only shared
libcurl library for i386 Linux platforms that is only 113 KiB in size, and an
FTP-only library that is 113 KiB in size (as of libcurl version 7.50.3, using
gcc 5.4.0).
You may find that statically linking libcurl to your application will result
in a lower total size than dynamically linking.
Note that the curl test harness can detect the use of some, but not all, of
the statements suggested above. Use will cause tests relying on
those features to fail. The test harness can be manually forced to skip the
relevant tests by specifying certain key words on the command
line. Following is a list of appropriate key words:
- !cookies
- !—manual
- !HTTP\ proxy !proxytunnel !SOCKS4 !SOCKS5
PORTS
This is a probably incomplete list of known CPU architectures and operating
systems that curl has been compiled for. If you know a system curl compiles
and runs on, that isn’t listed, please let us know!
PROGRESS METER
curl normally displays a progress meter during operations, indicating the amount of transferred data, transfer speeds and estimated time left, etc. The progress meter displays number of bytes and the speeds are in bytes per second. The suffixes (k, M, G, T, P) are 1024 based. For example 1k is 1024 bytes. 1M is 1048576 bytes.
curl displays this data to the terminal by default, so if you invoke curl to do an operation and it is about to write data to the terminal, it disables the progress meter as otherwise it would mess up the output mixing progress meter and response data.
If you want a progress meter for HTTP POST or PUT requests, you need to redirect the response output to a file, using shell redirect (>), or similar.
This does not apply to FTP upload as that operation does not spit out any response data to the terminal.
If you prefer a progress «bar» instead of the regular meter, -#, —progress-bar is your friend. You can also disable the progress meter completely with the option.
Building libcurl.dll on Windows
Required tools
- Microsoft Librarian (lib.exe)
- Sample program app.d
import std.net.curl; import std.stdio; void main() { writeln(get("https://google.com/")); }
Building libcurl.dll 32 bit with SSL support
- Create directory C:\BUILD
- Save the following batch file as C:\BUILD\build-curl32.bat
- Run build-curl32 from Windows command prompt
@echo off : 1) Path to MinGW\bin : 2) Path to Digital Mars's implib.exe SET PATH=C:\Dev\MinGW\bin;C:\Dev\dm\bin; SET ZLIB_PATH=C:\BUILD\zlib-1.2.10 SET INSTALL_DIR=C:\D\dmd2\windows : --------------------------------------------------------------- : Delete object files from previous build del /S zlib-1.2.10\*.o curl-7.52.1\*.o curl-7.52.1\*.res cd zlib-1.2.10 mingw32-make -fwin32/Makefile.gcc cd .. cd curl-7.52.1 mingw32-make -C lib -f Makefile.m32 CFG=mingw32-winssl-zlib-ipv6 LDFLAGS=-static strip -s lib\libcurl.dll mkdir %INSTALL_DIR%\bin %INSTALL_DIR%\lib copy lib\libcurl.dll %INSTALL_DIR%\bin implib /system %INSTALL_DIR%\lib\curl.lib lib\libcurl.dll cd .. : Build sample SET PATH=%INSTALL_DIR%\bin dmd app.d -ofapp32.exe app32
Building libcurl.dll 64 bit with SSL support
- Create directory C:\BUILD
- Save the following batch file as C:\BUILD\build-curl64.bat
- Run build-curl64 from Windows command prompt
@echo off : 1) Path to MinGW-w64\bin : 2) Path to Microsoft LIB.exe : 3) Path to pexports.exe (http://sourceforge.net/projects/mingw/files/MinGW/Extension/pexports/) SET PATH=C:\Dev\MinGW64\bin;C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\Bin\amd64;C:\Dev\MinGW\bin SET ZLIB_PATH=C:\BUILD\zlib-1.2.10 SET INSTALL_DIR=C:\D\dmd2\windows : --------------------------------------------------------------- : Delete object files from previous build del /S zlib-1.2.10\*.o curl-7.52.1\*.o curl-7.52.1\*.res cd zlib-1.2.10 mingw32-make -fwin32/Makefile.gcc cd .. cd curl-7.52.1 mingw32-make -C lib -f Makefile.m32 CFG=mingw32-winssl-zlib-ipv6 LDFLAGS=-static strip -s lib\libcurl.dll mkdir %INSTALL_DIR%\bin64 %INSTALL_DIR%\lib64 copy lib\libcurl.dll %INSTALL_DIR%\bin64 pexports lib\libcurl.dll > curl.def lib /MACHINE:X64 /DEF:curl.def /OUT:%INSTALL_DIR%\lib64\curl.lib cd .. : Build sample SET PATH=%INSTALL_DIR%\bin64;%INSTALL_DIR%\bin dmd -m64 app.d -ofapp64.exe app64
Использования cURL онлайн
Да, это возможно. Вы можете выполнить cURL удаленно с помощью следующих инструментов.Online CURL — компактный инструмент для извлечения URL-адреса онлайн и добавления следующих параметров.
--connect-timeout --cookie --data --header --head --location --max-time --proxy --request --user --url --user-agent
Пример вывода:
cURL command line builder–позволяет создать команду cURL, с помощью которой можно ввести информацию в пользовательский интерфейс.
cURL — полезная утилита для устранения проблем с подключением в режиме реального времени.
Пожалуйста, оставьте свои отзывы по текущей теме статьи. За комментарии, отклики, подписки, лайки, дизлайки низкий вам поклон!
Forms explained
Forms are the general way a website can present a HTML page with fields for the user to enter data in, and then press some kind of ‘OK’ or ‘Submit’ button to get that data sent to the server. The server then typically uses the posted data to decide how to act. Like using the entered words to search in a database, or to add the info in a bug tracking system, display the entered address on a map or using the info as a login-prompt verifying that the user is allowed to see what it is about to see.
Of course there has to be some kind of program on the server end to receive the data you send. You cannot just invent something out of the air.
Следовать за редиректами
Сервер Google сообщил нам, что страница перемещена (301 Moved Permanently), и теперь надо запрашивать страницу . С помощью опции укажем CURL следовать редиректам:
> curl -L google.com <!doctype html> <html itemscope="" itemtype="http://schema.org/WebPage" lang="ru"> <head> <meta content="Поиск информации в интернете: веб страницы, картинки, видео и многое другое." name="description"> <meta content="noodp" name="robots"> <meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image"> <meta content="origin" name="referrer"> <title>Google</title> ..........
Using BSD-style lwIP instead of Winsock TCP/IP stack in Win32 builds
In order to compile libcurl and curl using BSD-style lwIP TCP/IP stack it is
necessary to make definition of preprocessor symbol visible to
libcurl and curl compilation processes. To set this definition you have the
following alternatives:
- Modify and
- Modify
- Modify the «Preprocessor Definitions» in the libcurl project
Note: The pre-processor settings can be found using the Visual Studio IDE
under «Project -> Settings -> C/C++ -> General» in VC6 and «Project ->
Properties -> Configuration Properties -> C/C++ -> Preprocessor» in later
versions.
Once that libcurl has been built with BSD-style lwIP TCP/IP stack support, in
order to use it with your program it is mandatory that your program includes
lwIP header file (or another lwIP header that includes this)
before including any libcurl header. Your program does not need the
preprocessor definition which is for libcurl internals only.
This BSD-style lwIP TCP/IP stack support must be considered experimental given
that it has been verified that lwIP 1.4.0 still needs some polish, and libcurl
might yet need some additional adjustment, caveat emptor.
Using BSD-style lwIP instead of Winsock TCP/IP stack in Win32 builds
In order to compile libcurl and curl using BSD-style lwIP TCP/IP stack it is necessary to make definition of preprocessor symbol visible to libcurl and curl compilation processes. To set this definition you have the following alternatives:
- Modify and
- Modify
- Modify the «Preprocessor Definitions» in the libcurl project
Note: The pre-processor settings can be found using the Visual Studio IDE under «Project -> Settings -> C/C++ -> General» in VC6 and «Project -> Properties -> Configuration Properties -> C/C++ -> Preprocessor» in later versions.
Once that libcurl has been built with BSD-style lwIP TCP/IP stack support, in order to use it with your program it is mandatory that your program includes lwIP header file (or another lwIP header that includes this) before including any libcurl header. Your program does not need the preprocessor definition which is for libcurl internals only.
Compilation has been verified with lwIP 1.4.0 and contrib-1.4.0.
This BSD-style lwIP TCP/IP stack support must be considered experimental given that it has been verified that lwIP 1.4.0 still needs some polish, and libcurl might yet need some additional adjustment, caveat emptor.
POST запрос при помощи cURL
Теперь давайте отправим post запрос на адрес https://httpbin.org/anything
$url = 'https://httpbin.org/anything'; // url, на который отправляется запрос $post_data = [ // поля нашего запроса 'field1' => 'val_1', 'field2' => 'val_2', ]; $headers = []; // заголовки запроса $post_data = http_build_query($post_data); $curl = curl_init(); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_VERBOSE, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_POST, true); // true - означает, что отправляется POST запрос $result = curl_exec($curl);
Отлично, с GET и POST запросами в cURL мы немного освоились.
Теперь разберемся с заголовками, которые мы можем отсылать в запросе.
Заголовки устанавливаются при помощи опции CURLOPT_HTTPHEADER
Чтобы получше узнать, для чего нужна эта опция давайте попробуем отправить POST запрос в формате JSON