Curl ошибка 400

It seems like im getting a problem when Im trying to send a request to a server in php. The http api request is something like this:

http://api.ean.com/ean-services/rs/hotel/v3/avail?minorRev14&apiKey=p9ycn9cxb2zp3k3gfvbf5aym&cid=55505&locale=en_US&hotelId=122212&stateProvinceCode=%20NV%C2%A4cyCode=USD&arrivalDate=12/27/2012&departureDate=12/28/2012&room1=2,&room2=2,18,15&room3=3,16,16,15&room4=3,&includeDetails=true&includeRoomImages=true

I have the following part of my code in php where I believe the error is occuring:

$url = 'http://api.ean.com/ean-services/rs/hotel/v3/avail?minorRev14';
$url .= '&apiKey=p9ycn9cxb2zp3k3gfvbf5aym';
$url .= '&cid=55505';
$url .= '&locale=' . $locale . '&hotelId=' . $hotelid . '&stateProvinceCode=' . $state . '&currencyCode=USD';

$url .= '&arrivalDate=' . $datefr . '&departureDate=' . $dateto . '&' . $details . '&includeDetails=true&includeRoomImages=true';
$header = "Accept: application/json";

$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_ENCODING, "gzip");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$retValue = curl_exec($ch);
$response = json_decode(curl_exec($ch));
$ee       = curl_getinfo($ch);
print_r($ee);

print_r($retValue);

This is what I get from the print_r(curl_getinfo($ch)) statement:

Array (
    [url] => http://api.ean.com/ean-services/rs/hotel/v3/avail?minorRev14&apiKey=p9ycn9cxb2zp3k3gfvbf5aym&cid=55505&locale=en_US&hotelId=122212&stateProvinceCode= NV¤cyCode=USD&arrivalDate=12/27/2012&departureDate=12/28/2012&room1=2,&room2=2,18,15&room3=3,16,16,15&room4=3,&includeDetails=true&includeRoomImages=true
    [content_type] => text/html
    [http_code] => 400
    [header_size] => 181
    [request_size] => 340
    [filetime] => -1
    [ssl_verify_result] => 0
    [redirect_count] => 0
    [total_time] => 0.469
    [namelookup_time] => 0
    [connect_time] => 0.125
    [pretransfer_time] => 0.125
    [size_upload] => 0
    [size_download] => 349
    [speed_download] => 744
    [speed_upload] => 0
    [download_content_length] => 349
    [upload_content_length] => 0
    [starttransfer_time] => 0.469
    [redirect_time] => 0
    [certinfo] => Array ( )
    [redirect_url] =>
)

I’m not sure what the solution can be and I have been looking at this problem for awhile now hopefully someone can help me thanks :)

Проблема вот в чем:
Отправляю POST запрос cURL-ом, на другой стороне PHP скрипт принимает запрос и согласно переданным данным в HEADER-е выполняет определенные действия, выдавая ответ.
До сегодняшнего дня все прекрасно работало, проблем не было. Теперь — беда.
Запускаю этот скрипт с локалки (Open Server) — все работает, запускаю с сервера — выдает 400 Bad request.
Может быть важно, на сервере два аккаунта, но в одном личном кабинете. Запрос идет от одного к другому.
Код:

$headers = array(
		"purpose: har_top_index"
	);
	$ch = curl_init('<абсолютный путь к файлу>');
	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$result = curl_exec($ch);
	curl_close($ch);
	$result = json_decode($result, true);

Подскажите пожалуйста, что делаю не так? Или все же это сервер тупит?

  1. 1.

    Unsupported protocol. This build of curl has no support for this protocol. Usually this happens because the URL was misspelled to use a scheme part that either has a space in front of it or spells http like htpt or similar. Another common mistake is that you use a libcurl installation that was built with one or more protocols disabled and you now ask libcurl to use one of those protocols that were disabled in the build.

  2. 2.

    Failed to initialize. This is mostly an internal error or a problem with the libcurl installation or system libcurl runs in.

  3. 3.

    URL malformed. The syntax was not correct. This happens when you mistype a URL so that it ends up wrong, or in rare situations you are using a URL that is accepted by another tool that curl does not support only because there is no universal URL standard that everyone adheres to.

  4. 4.

    A feature or option that was needed to perform the desired request was not enabled or was explicitly disabled at build-time. To make curl able to do this, you probably need another build of libcurl.

  5. 5.

    Couldn’t resolve proxy. The address of the given proxy host could not be resolved. Either the given proxy name is just wrong, or the DNS server is misbehaving and does not know about this name when it should or perhaps even the system you run curl on is misconfigured so that it does not find/use the correct DNS server.

  6. 6.

    Couldn’t resolve host. The given remote host’s address was not resolved. The address of the given server could not be resolved. Either the given host name is just wrong, or the DNS server is misbehaving and does not know about this name when it should or perhaps even the system you run curl on is misconfigured so that it does not find/use the correct DNS server.

  7. 7.

    Failed to connect to host. curl managed to get an IP address to the machine and it tried to setup a TCP connection to the host but failed. This can be because you have specified the wrong port number, entered the wrong host name, the wrong protocol or perhaps because there is a firewall or another network equipment in between that blocks the traffic from getting through.

  8. 8.

    Unknown FTP server response. The server sent data curl could not parse. This is either because of a bug in curl, a bug in the server or because the server is using an FTP protocol extension that curl does not support. The only real work-around for this is to tweak curl options to try it to use other FTP commands that perhaps will not get this unknown server response back.

  9. 9.

    FTP access denied. The server denied login or denied access to the particular resource or directory you wanted to reach. Most often you tried to change to a directory that does not exist on the server. The directory of course is what you specify in the URL.

  10. 10.

    FTP accept failed. While waiting for the server to connect back when an active FTP session is used, an error code was sent over the control connection or similar.

  11. 11.

    FTP weird PASS reply. Curl could not parse the reply sent to the PASS request. PASS in the command curl sends the password to the server with, and even anonymous connections to FTP server actually sends a password — a fixed anonymous string. Getting a response back from this command that curl does not understand is a strong indication that this is not an FTP server at all or that the server is badly broken.

  12. 12.

    During an active FTP session (PORT is used) while waiting for the server to connect, the timeout expired. It took too long for the server to get back. This is usually a sign that something is preventing the server from reaching curl successfully. Like a firewall or other network arrangements. .

  13. 13.

    Unknown response to FTP PASV command, Curl could not parse the reply sent to the PASV request. This is a strange server. PASV is used to setup the second data transfer connection in passive mode, see the

    FTP uses two connections

    section for more on that. You might be able to work-around this problem by using PORT instead, with the --ftp-port option.

  14. 14.

    Unknown FTP 227 format. Curl could not parse the 227-line the server sent. This is most certainly a broken server. A 227 is the FTP server’s response when sending back information on how curl should connect back to it in passive mode. You might be able to work-around this problem by using PORT instead, with the --ftp-port option.

  15. 15.

    FTP cannot get host. Couldn’t use the host IP address we got in the 227-line. This is most likely an internal error.

  16. 16.

    HTTP/2 error. A problem was detected in the HTTP2 framing layer. This is somewhat generic and can be one out of several problems, see the error message for details.

  17. 17.

    FTP could not set binary. Couldn’t change transfer method to binary. This server is broken. curl needs to set the transfer to the correct mode before it is started as otherwise the transfer cannot work.

  18. 18.

    Partial file. Only a part of the file was transferred. When the transfer is considered complete, curl will verify that it actually received the same amount of data that it was told before-hand that it was going to get. If the two numbers do not match, this is the error code. It could mean that curl got fewer bytes than advertised or that it got more. curl itself cannot know which number that is wrong or which is correct. If any.

  19. 19.

    FTP could not download/access the given file. The RETR (or similar) command failed. curl got an error from the server when trying to download the file.

  20. 21.

    Quote error. A quote command returned an error from the server. curl allows several different ways to send custom commands to a IMAP, POP3, SMTP or FTP server and features a generic check that the commands work. When any of the individually issued commands fails, this is exit status is returned. The advice is generally to watch the headers in the FTP communication to better understand exactly what failed and how.

  21. 22.

    HTTP page not retrieved. The requested URL was not found or returned another error with the HTTP error code being 400 or above. This return code only appears if -f, --fail is used.

  22. 23.

    Write error. Curl could not write data to a local filesystem or similar. curl receives data chunk by chunk from the network and it stores it like at (or writes it to stdout), one piece at a time. If that write action gets an error, this is the exit status.

  23. 25.

    Upload failed. The server refused to accept or store the file that curl tried to send to it. This is usually due to wrong access rights on the server but can also happen due to out of disk space or other resource constraints. This error can happen for many protocols.

  24. 26.

    Read error. Various reading problems. The inverse to exit status 23. When curl sends data to a server, it reads data chunk by chunk from a local file or stdin or similar, and if that reading fails in some way this is the exit status curl will return.

  25. 27.

    Out of memory. A memory allocation request failed. curl needed to allocate more memory than what the system was willing to give it and curl had to exit. Try using smaller files or make sure that curl gets more memory to work with.

  26. 28.

    Operation timeout. The specified time-out period was reached according to the conditions. curl offers several

    timeouts

    , and this exit code tells one of those timeout limits were reached. Extend the timeout or try changing something else that allows curl to finish its operation faster. Often, this happens due to network and remote server situations that you cannot affect locally.

  27. 30.

    FTP PORT failed. The PORT command failed. Not all FTP servers support the PORT command; try doing a transfer using PASV instead. The PORT command is used to ask the server to create the data connection by connecting back to curl. See also the

    FTP uses two connections

    section.

  28. 31.

    FTP could not use REST. The REST command failed. This command is used for resumed FTP transfers. curl needs to issue the REST command to do range or resumed transfers. The server is broken, try the same operation without range/resume as a crude work-around.

  29. 33.

    HTTP range error. The range request did not work. Resumed HTTP requests are not necessary acknowledged or supported, so this exit code signals that for this resource on this server, there can be no range or resumed transfers.

  30. 34.

    HTTP post error. Internal post-request generation error. If you get this error, please report the exact circumstances to the curl project.

  31. 35.

    A TLS/SSL connect error. The SSL handshake failed. The SSL handshake can fail due to numerous different reasons so the error message may offer some additional clues. Maybe the parties could not agree to a SSL/TLS version, an agreeable cipher suite or similar.

  32. 36.

    Bad download resume. Could not continue an earlier aborted download. When asking to resume a transfer that then ends up not possible to do, this error can get returned. For FILE, FTP or SFTP.

  33. 37.

    Couldn’t read the given file when using the FILE:// scheme. Failed to open the file. The file could be non-existing or is it a permission problem perhaps?

  34. 38.

    LDAP cannot bind. LDAP «bind» operation failed, which is a necessary step in the LDAP operation and thus this means the LDAP query could not be performed. This might happen because of wrong username or password, or for other reasons.

  35. 39.

    LDAP search failed. The given search terms caused the LDAP search to return an error.

  36. 42.

    Aborted by callback. An application told libcurl to abort the operation. This error code is not generally made visible to users and not to users of the curl tool.

  37. 43.

    Bad function argument. A function was called with a bad parameter — this return code is present to help application authors to understand why libcurl cannot perform certain actions and should never be return by the curl tool. Please file a bug report to the curl project if this happens to you.

  38. 45.

    Interface error. A specified outgoing network interface could not be used. curl will typically decide outgoing network and IP addresses by itself but when explicitly asked to use a specific one that curl cannot use, this error can occur.

  39. 47.

    Too many redirects. When following HTTP redirects, libcurl hit the maximum number set by the application. The maximum number of redirects is unlimited by libcurl but is set to 50 by default by the curl tool. The limit is present to stop endless redirect loops. Change the limit with --max-redirs.

  40. 48.

    Unknown option specified to libcurl. This could happen if you use a curl version that is out of sync with the underlying libcurl version. Perhaps your newer curl tries to use an option in the older libcurl that was not introduced until after the libcurl version you are using but is known to your curl tool code as that is newer. To decrease the risk of this and make sure it does not happen: use curl and libcurl of the same version number.

  41. 49.

    Malformed telnet option. The telnet options you provide to curl was not using the correct syntax.

  42. 51.

    The server’s SSL/TLS certificate or SSH fingerprint failed verification. curl can then not be sure of the server being who it claims to be. See the

    using TLS with curl

    section for more TLS details and

    using SCP and SFTP with curl

    for more SSH specific details.

  43. 52.

    The server did not reply anything, which in this context is considered an error. When an HTTP(S) server responds to an HTTP(S) request, it will always return something as long as it is alive and sound. All valid HTTP responses have a status line and responses header. Not getting anything at all back is an indication the server is faulty or perhaps that something prevented curl from reaching the right server or that you are trying to connect to the wrong port number etc.

  44. 53.

    SSL crypto engine not found.

  45. 54.

    Cannot set SSL crypto engine as default.

  46. 55.

    Failed sending network data. Sending data over the network is a crucial part of most curl operations and when curl gets an error from the lowest networking layers that the sending failed, this exit status gets returned. To pinpoint why this happens, some serious digging is usually required. Start with enabling verbose mode, do tracing and if possible check the network traffic with a tool like Wireshark or similar.

  47. 56.

    Failure in receiving network data. Receiving data over the network is a crucial part of most curl operations and when curl gets an error from the lowest networking layers that the receiving of data failed, this exit status gets returned. To pinpoint why this happens, some serious digging is usually required. Start with enabling verbose mode, do tracing and if possible check the network traffic with a tool like Wireshark or similar.

  48. 58.

    Problem with the local certificate. The client certificate had a problem so it could not be used. Permissions? The wrong pass phrase?

  49. 59.

    Couldn’t use the specified SSL cipher. The cipher names need to be specified exact and they are also unfortunately specific to the particular TLS backend curl has been built to use. For the current list of support ciphers and how to write them, see the online docs at

    https://curl.se/docs/ssl-ciphers.html

    .

  50. 60.

    Peer certificate cannot be authenticated with known CA certificates. This usually means that the certificate is either self-signed or signed by a CA (Certificate Authority) that is not present in the CA store curl uses.

  51. 61.

    Unrecognized transfer encoding. Content received from the server could not be parsed by curl.

  52. 63.

    Maximum file size exceeded. When curl has been told to restrict downloads to not do it if the file is too big, this is the exit code for that condition.

  53. 64.

    Requested SSL (TLS) level failed. In most cases this means that curl failed to upgrade the connection to TLS when asked to.

  54. 65.

    Sending the data requires a rewind that failed. In some situations curl needs to rewind in order to send the data again and if this can’t be done, the operations fails.

  55. 66.

    Failed to initialize the OpenSSL SSL Engine. This can only happen when OpenSSL is used and would signify a serious internal problem.

  56. 67.

    The user name, password, or similar was not accepted and curl failed to log in. Verify that the credentials are provided correctly and that they are encoded the right way.

  57. 68.

    File not found on TFTP server.

  58. 69.

    Permission problem on TFTP server.

  59. 70.

    Out of disk space on TFTP server.

  60. 72.

    Unknown TFTP transfer ID.

  61. 73.

    File already exists (TFTP).

  62. 77.

    Problem with reading the SSL CA cert. The default or specified CA cert bundle could not be read/used to verify the server certificate.

  63. 78.

    The resource (file) referenced in the URL does not exist.

  64. 79.

    An unspecified error occurred during the SSH session. This sometimes indicate an incompatibility problem between the SSH libcurl curl uses and the SSH version used by the server curl speaks to.

  65. 80.

    Failed to shut down the SSL connection.

  66. 82.

    Could not load CRL file, missing or wrong format

  67. 83.

    TLS certificate issuer check failed. The most common reason for this is that the server did not send the proper intermediate certificate in the TLS handshake.

  68. 84.

    The FTP PRET command failed. This is a non-standard command and far from all servers support it.

  69. 85.

    RTSP: mismatch of CSeq numbers

  70. 86.

    RTSP: mismatch of Session Identifiers

  71. 87.

    Unable to parse FTP file list. The FTP directory listing format used by the server could not be parsed by curl. FTP wildcards can not be used on this server.

  72. 88.

    FTP chunk callback reported error

  73. 89.

    No connection available, the session will be queued

  74. 90.

    SSL public key does not matched pinned public key. Either you provided a bad public key, or the server has changed.

  75. 91.

    Invalid SSL certificate status. The server did not provide a proper valid certificate in the TLS handshake.

  76. 92.

    Stream error in HTTP/2 framing layer. This is usually an unrecoverable error, but trying to force curl to speak HTTP/1 instead might circumvent it.

  77. 93.

    An API function was called from inside a callback. If the curl tool returns this, something has gone wrong internally

  78. 95.

    HTTP/3 layer error. This is somewhat generic and can be one out of several problems, see the error message for details.

  79. 96.

    QUIC connection error. This error may be caused by an TLS library error. QUIC is the transport protocol used for HTTP/3.

  80. 97.

    Proxy handshake error. Usually that means that a SOCKS proxy did not play along.

  81. 98.

    A TLS client certificate is required but was not provided.

  82. 99.

    An internal call to poll() or select() returned error that is not recoverable.

За последние 24 часа нас посетили 10079 программистов и 946 роботов. Сейчас ищут 664 программиста …


  1. bigB

    С нами с:
    6 май 2016
    Сообщения:
    11
    Симпатии:
    0

    Вообщем-то со стороны сервера пытаюсь переводить текст с Яндекс апи. Столкнулся с проблемой, что в зависимости от текста всплывает 400 ошибка.
    Например при Mad has всё нормально, а при Mad Has ошибка, при Mad Qwe всё нормально.

    1. $tr_text = $_GET[«tr_text»];
    2. $tr_type = $_GET[«tr_type»];
    3. $url = «https://translate.yandex.net/api/v1.5/tr.json/translate?key=trnsl.1.1.20160622T182932Z.c2bfc0460fb9cc92.a72ddd223b90ec7d579cff18b9d3881ede982356&text=». $tr_text .«&lang=». $tr_type;
    4. //echo $res->text[0] . «<br>»;
    5.     <input style=»width: 300px» type=»text» name=»tr_text» value=»<?echo $_GET[‘tr_text’];?>«>
    6.     <input style=»width: 50px» type=»text» name=»tr_type» value=»<?echo $_GET[‘tr_type’];?>«>


  2. askanim

    С нами с:
    7 апр 2016
    Сообщения:
    2.200
    Симпатии:
    166
    Адрес:
    GABRIEL

    С конкретной задачей не сталкивался, но попробуй полученный переменные перевести в один регистр. И уже их отправлять яшке в нижнем регистре

    1. $str = «У Мэри Был Маленький Ягненок и Она Его Очень ЛЮБИЛА»;
    2. echo $str; // Выведет у мэри был маленький ягненок и она его очень любила

    — Добавлено —
    А ещё как бы у тебя в url идёт разрыв строки… Когда ты передаёшь предложение вот выведи свой url который ты получаешь в результате.
    Там у тебя в твоём предложение будут разрывы строк. Поэтому скорее всего и error 404. Потому что url c разрывной строкой идёт. Может там в апи написано что между каждым словом какие нибудь знаки должны стоять ?


  3. mr.akv

    mr.akv
    Активный пользователь

    С нами с:
    31 мар 2015
    Сообщения:
    1.604
    Симпатии:
    206

    есть предложение, готовить адресную строку через urlencode()


  4. askanim

    С нами с:
    7 апр 2016
    Сообщения:
    2.200
    Симпатии:
    166
    Адрес:
    GABRIEL

    А яша её раскодирует ?
    — Добавлено —
    Я просто не работал с апи яндекса


  5. askanim

    С нами с:
    7 апр 2016
    Сообщения:
    2.200
    Симпатии:
    166
    Адрес:
    GABRIEL

    Потому что у тебя, там разрыв строки в url шёл в результате.


  6. bigB

    С нами с:
    6 май 2016
    Сообщения:
    11
    Симпатии:
    0

    Почему тогда «M H» выводило ошибку, а «M A», например, нет?


  7. Ganzal

    Команда форума
    Модератор

    С нами с:
    15 мар 2007
    Сообщения:
    9.902
    Симпатии:
    969

    в адресную строку браузера? браузер перед запросом приводил адрес к корректному виду.


  8. askanim

    С нами с:
    7 апр 2016
    Сообщения:
    2.200
    Симпатии:
    166
    Адрес:
    GABRIEL

    Ну где то может проскакивало, не знаю, я не сталкивался ещё с такой задачей. Но ты попробуй создай url с пробелами и вбей в строку браузера, что в результате будет?


  9. bigB

    С нами с:
    6 май 2016
    Сообщения:
    11
    Симпатии:
    0

    Проблема со стороны сервера была конкретно в определенных символах, M A нормально проходило в любом случае, M H выбивало ошибку.


  10. mr.akv

    mr.akv
    Активный пользователь

    С нами с:
    31 мар 2015
    Сообщения:
    1.604
    Симпатии:
    206

    а что сейчас не может раскодировать такие строки?)


  11. mr.akv

    mr.akv
    Активный пользователь

    С нами с:
    31 мар 2015
    Сообщения:
    1.604
    Симпатии:
    206

    @askanim, с АПИ работать радость. Если АПИ нормально документированный.


  12. askanim

    С нами с:
    7 апр 2016
    Сообщения:
    2.200
    Симпатии:
    166
    Адрес:
    GABRIEL

    Я делал какую то задачу для собирания контента с wiki что-то посидел пока делал…

Comments

@T200proX7

bagder

added a commit
that referenced
this issue

Sep 11, 2021

@bagder

It should not refer to the uagent string that is allocated and created
for the end server http request, as that pointer may be cleared on
subsequent CONNECT requests.

Added test case 1184 to verify.

Reported-by: T200proX7
Fixes #7705

bagder

added a commit
that referenced
this issue

Sep 11, 2021

@bagder

It should not refer to the uagent string that is allocated and created
for the end server http request, as that pointer may be cleared on
subsequent CONNECT requests.

Added test case 1184 to verify.

Reported-by: T200proX7 on github
Fixes #7705

bagder

added a commit
that referenced
this issue

Sep 13, 2021

@bagder

It should not refer to the uagent string that is allocated and created
for the end server http request, as that pointer may be cleared on
subsequent CONNECT requests.

Added test case 1184 to verify.

Reported-by: T200proX7 on github
Fixes #7705
Closes #7707

Понравилась статья? Поделить с друзьями:
  • Curl игнорировать ssl ошибку php
  • Curl php получить ошибку
  • Curl error 6 could not resolve host ошибка
  • Curl 301 ошибка
  • Cureit ошибка удаления