Отправка post запросов html

HTTP POST Request Method

POST is an HTTP method designed to send data to the server from an HTTP client. The HTTP POST method requests the web server accept the data enclosed in the body of the POST message. HTTP POST method is often used when submitting login or contact forms or uploading files and images to the server.

What is HTTP?

The Hypertext Transfer Protocol (HTTP) is designed to support communication between clients (browser or application) and web servers. HTTP is designed to send information in a format that both the client and the server can understand. HTTP works as a stateless request-response protocol between the client and the web server. HTTP is based on several request methods, or «verbs», including the HTTP POST and HTTP GET request methods, and several others. Web browsers usually only use HTTP GET and HTTP POST, but RESTful desktop and mobile applications use many others. Sending data to the server over HTTP can be done using several HTTP request methods. The HTTP POST request method is one of them. The HTTP POST method asks the web server to accept the data contained in the body of the message. The data type in the HTTP POST body is indicated by the Content-Type header.

Читайте также:  Как реализовать поиск php

What is the HTTP POST request method used for?

The HTTP POST method is used to create or add a resource on the server. Typically, the POST request adds a new resource to the server, while the PUT request replaces an existing resource on the server. For example, the HTTP POST request method is used by browsers when submitting HTML form data to the server or when submitting data using jQuery/AJAX requests. Unlike GET and HEAD requests, the HTTP POST requests may change the server state.

Sending HTTP headers with HTTP POST request

If you are sending data with your POST request, you must provide the Content-Type and Content-Length HTTP headers that indicate the type and size of the data in your POST message. These HTTP headers will help the server interpret and process the sent data correctly. Alternatively, you can omit the Content-Length header for your POST request and use the Transfer-Encoding header instead. If the Content-Length and Transfer-Encoding headers are missing, the connection MUST be closed at the end of the response.

POST /post HTTP/1.1 Content-Type: application/json Content-Length: 1024 Host: reqbin.com

Sending data with HTTP POST method

To send data using the HTTP POST method, you must include the data in the body of the HTTP POST message and specify the MIME type of the data with a Content-Type header. Below is an example of an HTTP POST request to send JSON data to the server.

The size and data type for HTTP POST requests is not limited. But you must specify the data type in the Content-Type header and the data size in the Content-Length header fields. The HTTP POST requests can also send data to the server using the URL parameters. In this case, you are limited to the maximum size of the URL, which is about 2000 characters (it depends on the browser).

Читайте также:  What does this means in javascript

The HTTP POST method is not idempotent, which means that sending an identical POST request multiple times may additionally affect the state or cause further side effects (eg. on financial transactions).

HTTP POST Request Example

The following HTTP POST request example demonstrates sending a POST request to the server. In this example, the ‘Content-Type: application/json’ request header indicates the media type of the resource, and the ‘Content-Length: 85’ request header indicates the size of the data in the request body.

POST /echo/post/json HTTP/1.1 Authorization: Bearer mt0dgHmLJMVQhvjpNXDyA83vA_Pxh33Y Accept: application/json Content-Type: application/json Content-Length: 85 Host: reqbin.com
HTTP/1.1 200 OK Content-Length: 19 Content-Type: application/json

Submitting HTML forms using the HTTP POST method

HTML forms are used to collect user input and submit it to a web server. There are two options for submitting web forms to the server: using the HTTP POST or HTTP GET methods. In the example below, the «method=POST» form attribute tells the browser to submit the webform using the HTTP POST method, and the «action=/login» attribute specifies the destination URL.

Sending HTTP POST requests with JavaScript

In JavaScript, you can send HTTP requests using the XMLHttpRequest object or the new Fetch web API. In the example below, we are making an HTTP POST request using the XMLHttpRequest object.

var url = "https://reqbin.com/echo/post/json"; var xhr = new XMLHttpRequest(); xhr.open("POST", url); xhr.setRequestHeader("Accept", "application/json"); xhr.setRequestHeader("Content-Type", "application/json"); xhr.onreadystatechange = function () < if (xhr.readyState === 4) < console.log(xhr.status); console.log(xhr.responseText); >>; xhr.send('');

Sending HTTP POST requests with Python

Python has an excellent «requests» library for making HTTP requests. Using the «requests» library, you can send POST requests with just a few lines of code.

import requests from requests.structures import CaseInsensitiveDict url = "https://reqbin.com/echo/post/json" headers = CaseInsensitiveDict() headers["Accept"] = "application/json" headers["Content-Type"] = "application/json" data = """ < "Id": 78912, "Customer": "Jason Sweet", >""" resp = requests.post(url, headers=headers, data=data) print(resp.status_code)

Sending HTTP POST requests with PHP

For PHP, you can use the built-in Curl module to make HTTP requests. Following is an example HTTP POST request to the ReqBin echo URL.

 DATA; curl_setopt($curl, CURLOPT_POSTFIELDS, $data); $resp = curl_exec($curl); curl_close($curl); var_dump($resp); ?>

HTTP POST Method Specification

Some notes on HTTP POST requests

  • POST requests are never cached
  • POST requests do not remain in the browser history
  • POST requests cannot be bookmarked

HTTP POST vs GET Method

GET POST
Browser BACK button/Reload Harmless Data will be re-submitted (the browser should alert the user that the data are about to be re-submitted)
Bookmarked Can be bookmarked Cannot be bookmarked
Cached Can be cached Not cached
History Parameters remain in browser history Parameters are not saved in browser history
Restrictions on data length Yes, when sending data, the GET method adds the data to the URL; and the length of a URL is limited (maximum URL length is 2048 characters) No restrictions
Restrictions on data type Only ASCII characters allowed No restrictions. Binary data is also allowed
Security GET is less secure compared to HTTP POST because data sent is part of the URL. Never use GET when sending passwords or other sensitive information!
Visibility Data is visible to everyone in the URL Data is not displayed in the URL

HTTP POST vs PUT Method

The fundamental difference between the HTTP POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. In contrast; the URI in a PUT request identifies the entity enclosed with the request. Practically speaking, POST is used to append a resource to an existing collection, while PUT is used to update an existing resource.

See also

Источник

Отправка данных формы

Сама форма обычно предназначена для получения от пользователя информации для дальнейшей пересылки её на сервер, где данные формы принимает программа-обработчик. Такая программа может быть написана на любом серверном языке программирования вроде PHP, Perl и др. Адрес программы указывается в атрибуте action тега , как показано в примере 1.

Пример 1. Отправка данных формы

В этом примере данные формы, обозначенные атрибутом name ( login и password ), будут переданы в файл по адресу /example/handler.php. Если атрибут action не указывать, то передача происходит на адрес текущей страницы.

Передача на сервер происходит двумя разными методами: GET и POST, для задания метода в теге используется атрибут method , а его значениями выступают ключевые слова get и post . Если атрибут method не задан, то по умолчанию данные отправляются на сервер методом GET. В табл. 1 показаны различия между этими методами.

Табл. 1. Различия между методами GET и POST

GET POST
Ограничение на объём4 КбОграничения задаются сервером.
Передаваемые данныеВидны сразу всем.Видны только при просмотре через расширения браузера или другими методами.
КэшированиеСтраницы с разными запросами считаются различными, их можно кэшировать как отдельные документы.Страница всегда одна.
ЗакладкиСтраницу с запросом можно добавить в закладки браузера и обратиться к ней позже.Страницы с разными запросами имеют один адрес, запрос повторить нельзя.

Какой метод используется легко определить по адресной строке браузера. Если в ней появился вопросительный знак и адрес стал похож на этот, то это точно GET.

Уникальное сочетание параметров в адресной строке однозначно идентифицирует страницу, так что страницы с адресами ?q=node/add и ?q=node считаются разными. Эту особенность используют системы управления контентом (CMS, Content management system) для создания множества страниц сайта. В реальности же используется один файл, который получает запрос GET и согласно ему формирует содержимое документа.

Ниже перечислены типовые области применения этих методов на сайтах.

GET

Передача небольших текстовых данных на сервер; поиск по сайту.

Поисковые системы, формы поиска по сайту всегда отправляются методом GET, это позволяет делиться результатами поиска с друзьями, слать ссылку по почте или выкладывать её на форуме.

POST

Пересылка файлов (фотографий, архивов, программ и др.); отправка комментариев; добавление и редактирование сообщений на форуме, блоге.

Работа с формой по умолчанию происходит в текущей вкладке браузера, при этом допустимо при отправке формы изменить этот параметр и открывать обработчик формы в новой вкладке или во фрейме. Такое поведение задаётся через «имя контекста», которое выступает значением атрибута target тега . Популярные значения это _blank для открытия формы в новом окне или вкладке, и имя фрейма, которое задаётся атрибутом name тега (пример 2).

Пример 2. Открытие формы во фрейме

В данном примере при нажатии на кнопку «Отправить» результат отправки формы открывается во фрейме с именем area .

Элементы формы традиционно располагаются внутри тега , тем самым определяя те данные, которые будут передаваться на сервер. В то же время в HTML5 есть возможность отделить форму от её элементов. Это сделано для удобства и универсальности, так, сложный макет может содержать несколько форм, которые не должны пересекаться меж собой или к примеру, некоторые элементы выводятся с помощью скриптов в одном месте страницы, а сама форма находится в другом. Связь между формой и её элементами происходит в таком случае через идентификатор формы, а к элементам следует добавить атрибут form со значением, равным этому идентификатору (пример 3).

Пример 3. Связывание формы с полями

В этом примере тег однозначно отождествляется через идентификатор auth , а к полям, которые следует отправить с помощью формы, добавляется form=»auth» . При этом поведение элементов не меняется, при нажатии на кнопку логин и пароль пересылаются на обработчик handler.php.

Хотя параметры передачи формы традиционно указываются в теге , их можно перенести и в кнопки отправки формы ( и ). Для этого применяется набор атрибутов formaction , formmethod , formenctype и formtarget , которые являются аналогами соответствующих атрибутов без приставки form. В примере 4 показано использование этих атрибутов.

Все новые атрибуты форм не поддерживаются некоторыми браузерами, в частности, Internet Explorer и Safari.

Источник

Оцените статью