- Using Forms for GET Requests
- URI Path Parameters
- Related Discussions
- Related Discussions
- HTTP-запрос методом GET.
- HTTP Request Methods
- HTTP Methods
- The GET Method
- The POST Method
- Compare GET vs. POST
- The PUT Method
- The HEAD Method
- The DELETE Method
- The PATCH Method
- The OPTIONS Method
- The CONNECT Method
- The TRACE Method
Using Forms for GET Requests
In the last video, you saw how anchors are used to trigger GET requests following a user click. In this video, you’ll see how search forms are commonly used to send data in an HTTP GET request. In particular, you’ll see how this data will be sent with the HTTP GET request as a query string in the URI of the request line.
URI Path Parameters
Sometimes when you’re searching using a web form, upon submitting a form, you won’t see a query string in the resulting URL in your address bar. Consider the hypothetical scenario of searching on example.com. Let’s say it has a search form that looks like this:
Now let’s say you enter «http» into the text input and submit the form. What you may observe when you finally see the search results is that the URL in your browser’s address bar says
What’s important to note here is that your browser hasn’t done anything different with your form or with its submission. Assuming it’s a standard HTML form, and the form’s submission is handled natively by the browser, here’s what likely happened:
- User enters «http» into text input
- User submits form
- Browser makes request as
HTTP/1.1 302 Found Location: /search/http
Given that a user would only see the bolded steps (1,2, and 7), it might appear that something peculiar is happening. In fact, in Chrome Developer Tools if you check the box next to «Preserve log», you’ll see this initial GET request with the query string on the URI (step 3), and the subsequent 302 response with a location header (step 5).
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
You need to sign up for Treehouse in order to download course files.
You need to sign up for Treehouse in order to set up Workspace
HTTP-запрос методом GET.
Одним из способов, как можно отправить запрос по протоколу HTTP к серверу, является запрос методом GET. Этот метод является самым распространенным и запросы к серверу чаще всего происходят с его использованием.
Самый простой способ, как можно создать запрос методом GET- это набрать URL-адрес в адресную строку браузера.
Если у вас есть желание погрузиться в тему серверного программирования глубже, все мои уроки здесь.
Браузер передаст серверу примерно следующую информацию:
GET / HTTP/1.1 Host: site.ru User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:18.0) Gecko/20100101 Firefox/18.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3 Accept-Encoding: gzip, deflate Cookie: wp-settings Connection: keep-alive
Запрос состоит из двух частей:
1. строка запроса (Request Line)
2. заголовки (Message Headers)
Обратите внимание, что GET запрос не имеет тела сообщения. Но, это не означает, что с его помощью мы не можем передать серверу никакую информацию. Это можно делать с помощью специальных GET параметров.
Чтобы добавить GET параметры к запросу, нужно в конце URL-адреса поставить знак «?» и после него начинать задавать их по следующему правилу:
имя_параметра1=значение_параметра1& имя_параметра2=значение_параметра2&…Разделителем между параметрами служит знак «&».
К примеру, если мы хотим передать серверу два значения, имя пользователя и его возраст, то это можно сделать следующей строкой:
http://site.ru/page.php?name=dima&age=27
Когда выполнен данный запрос, данные попадают в так называемую переменную окружения QUERY_STRING, из которой их можно получить на сервере с помощью серверного языка веб-программирования.
Вот пример, как это можно сделать на языке PHP.
"; echo "Ваш возраст: " . $_GET["age"] . "
"; ?>
Конструкция $_GET[«имя_параметра»] позволяет выводить значение переданного параметра.
В результате выполнения этого кода в браузере выведется:
Ваше имя: dima Ваш возраст: 27
Кстати, переходя по какой-либо ссылке, которая оформлена в HTML вот так:
мы тоже выполняем запрос к серверу методом GET.
Все мои уроки по серверному программированию здесь.
Чтобы оставить сообщение, зарегистрируйтесь/войдите на сайт через:
HTTP Request Methods
The Hypertext Transfer Protocol (HTTP) is designed to enable communications between clients and servers.
HTTP works as a request-response protocol between a client and server.
Example: A client (browser) sends an HTTP request to the server; then the server returns a response to the client. The response contains status information about the request and may also contain the requested content.
HTTP Methods
The two most common HTTP methods are: GET and POST.
The GET Method
GET is used to request data from a specified resource.
Note that the query string (name/value pairs) is sent in the URL of a GET request:
Some notes on GET requests:
- GET requests can be cached
- GET requests remain in the browser history
- GET requests can be bookmarked
- GET requests should never be used when dealing with sensitive data
- GET requests have length restrictions
- GET requests are only used to request data (not modify)
The POST Method
POST is used to send data to a server to create/update a resource.
The data sent to the server with POST is stored in the request body of the HTTP request:
POST /test/demo_form.php HTTP/1.1
Host: w3schools.com
Some notes on POST requests:
- POST requests are never cached
- POST requests do not remain in the browser history
- POST requests cannot be bookmarked
- POST requests have no restrictions on data length
Compare GET vs. POST
The following table compares the two HTTP methods: GET and POST.
GET | POST | |
---|---|---|
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 |
Encoding type | application/x-www-form-urlencoded | application/x-www-form-urlencoded or multipart/form-data. Use multipart encoding for binary data |
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 POST because data sent is part of the URL |
The PUT Method
PUT is used to send data to a server to create/update a resource.
The difference between POST and PUT is that PUT requests are idempotent. That is, calling the same PUT request multiple times will always produce the same result. In contrast, calling a POST request repeatedly have side effects of creating the same resource multiple times.
The HEAD Method
HEAD is almost identical to GET, but without the response body.
In other words, if GET /users returns a list of users, then HEAD /users will make the same request but will not return the list of users.
HEAD requests are useful for checking what a GET request will return before actually making a GET request — like before downloading a large file or response body.
The DELETE Method
The DELETE method deletes the specified resource.
The PATCH Method
The PATCH method is used to apply partial modifications to a resource.
The OPTIONS Method
The OPTIONS method describes the communication options for the target resource.
The CONNECT Method
The CONNECT method is used to start a two-way communications (a tunnel) with the requested resource.
The TRACE Method
The TRACE method is used to perform a message loop-back test that tests the path for the target resource (useful for debugging purposes).