7월29일 목요일 TIL[3]

김병훈·2021년 7월 29일
0

til

목록 보기
51/89

HTTP (HyperText Transfer Protocol)

  • 웹 브라우저와 웹 서버의 소통을 위해 디자인 되었다.
  • 전통적인 클-서 모델에서 클라이언트가 HTTP messages 양식에 맞춰 요청을 보내면, 서버도 HTTP messages 양식에 맞춰 응답한다.
  • 특정 상태를 유지하지 않는 특징이 있다.
    • HTTP의 특징 : Stateless (무상태성)

HTTP Messages

  • 클라이언트와 서버 사이에서 데이터가 교환 되는 방식
    • 요청(Requests)
    • 응답(Responses)
  • HTTP messages 는 몇 줄의 텍스트 정보로 구성된다.개발자는 직접 작성할 필요가 없고, 구성파일, API, 기타 interface에서 HTTP messages를 자동으로 완성한다.
  • 요청과 응답은 다음과 같은 유사한 구조를 가진다
    • start line
      • 요청이나 응답의 상태를 나타낸다.
      • 항상 첫 번째 줄에 위치한다.
      • 응답에서는 status line이라고 한다.
    • HTTP headers
      • 요청을 지정한다
      • 메시지에 포함된 본문을 설명하는 헤더의 집합이다.
    • empty line
      • 헤더와 본문을 구분하는 빈 줄이 있다.
    • body
      • 요청과 관련된 데이터나 응답과 관련된 데이터 또는 문서를 포함한다.
      • 요청과 응답의 유형에 따라 선택적으로 사용한다.
  • 이 중 start line과 HTTP headers를 묶어 요청이나 응답의 헤드라고하고, payload는 body라고 부른다.

요청

Start Line

  • HTTP 요청은 클라이언트가 서버에 보내는 메시지이다.
    1. 수행할 작업 (GET, PUT, POST) 이나 방식(HEAD, OPTIONS) 를 설명하는 HTTP method를 나타낸다.
    • 예를 들어 GET method는 리소스를 받아야하고, POST method는 데이터를 서버로 전송한다.
    1. 요청 대상 (URL / URI) 또는 프로토콜, 포트, 도메인의 절대 경로는 요청 컨텍스트에 작성된다. 이 요청형식은 HTTP method마다 다르다.
      • origin 형식: ?와 쿼리 문자열이 붙는 절대 경로입니다. POST, GET, HEAD, OPTIONS 등의 method와 함께 사용한다.
        POST / HTTP 1.1 , GET /background.png HTTP/1.0 , HEAD /test.html?query=alibaba HTTP/1.1 , OPTIONS /anypage.html HTTP/1.0
      • absolute 형식 : 완전한 URL 형식으로, 프록시에 연결하는 경우 대부분 GET method와 함께 사용한다.
        GET http://developer.mozilla.org/en-US/docs/Web/HTTP/Messages HTTP/1.1
      • authority 형식: 도메인 이름과 포트 번호로 이루어진 URL의 authority component 입니다. HTTP 터널을 구축하는 경우, CONNECT와 함께 사용할 수 있다. CONNECT developer.mozilla.org:80 HTTP/1.1
      • asterisk 형식: OPTIONS 와 함께 별표(*) 하나로 서버 전체를 표현한다.OPTIONS * HTTP/1.1
    1. HTTP 버전은 메시지의 다른 구조를 결정한다. 이를 위해 HTTP 버전을 함께 입력한다.

Headers

  • 요청에 Headers는 기본 구조를 따른다. 대소문자 구분 없는 문자열과 클론 , 값을 입력한다. 값은 헤더에 따라 다르다. 여러 종류의 헤더가 있고, 다음과 같이 그룹을 나눌 수 있다.
    • General headers
      • 메시지 전체에 적용된다.
    • Request headers
      • User-Agent, Accept-Type, Accept-Language과 같은 헤더는 요청을 보다 구체화한다.Referer처럼 컨텍스트를 제공하거나 If-None과 같이 조건에 따라 제약을 추가할 수 있다.
    • Entity headers
      • Content-Length와 같은 헤더는 body에 적용된다. body가 비어있는 경우, entity headers는 전송되지 않는다.

Body

  • 요청의 본문은 HTTP messages 구조의 마지막에 위치한다. 모든 요청에 body가 필요하지는 않다. GET, HEAD, DELETE, OPTIONS 처럼 서버에 리소스를 요청하는 경우에는 본문이 필요하지 않다. POST나PUT과 같은 일부 요청은 데이터를 업데이트하기 위해 사용한다. body는 두 종류로 나뉜다.
  • Single-resource bodies(단일-리소스 본문)
    • 헤더 두 개(Content-Type과 Content-Length)로 정의된 단일 파일로 구성된다.

응답(Response)

Status Line

  • 응답의 첫 줄은 Status line이라고 부르며 , 다음의 정보를 포함한다.
    1. version of current Protocol (HTTP/1.1)
    1. 상태코드
    • 요청의 결과를 나타낸다. (200, 302, 404..)
    1. 상태 텍스트
    • 상태 코드에 대한 설명
  • Status line 은 HTTP/1.1 404 Not Found.처럼 생겼다.

Headers

  • 응답에 들어가는 HTTP headers는 요청 헤더와 동일한 구조를 가지고 있다. 대소문자 구분 없는 문자열과 콜론 , 값을 입력한다. 값은 헤더에 따라 다르다. 요청의 헤더와 마찬가지로 몇 그룹으로 나눌 수 있다.
    • General headers
      • 메시지 전체에 적용한다.
    • Response headers
      • Vart, Accept-Ranges와 같이 상태 줄에 넣기에는 공간이 부족했던 추가 정보를 제공한다.
    • Entity headers
      • Content-Length와 같은 헤더는 body에 적용된다. body가 비어있는 경우, entity headers는 전송되지 않는다.

Body

  • 응답의 본문은 HTTP messages 구조의 마지막에 위치한다. 모든 응답에 body가 필요하진 않다. 201, 204같은 상태 코드를 가지는 응답에는 본문이 필요하지 않다. 응답의 body는 두 가지 종류로 나뉜다.
    • Single-resource bodies(단일-리소스 본문)
      • 길이가 알려진 단일-리소스 본문은 두 개의 헤더(Content-Type, Content-Length)로 정의한다.
      • 길이를 모르는 단일 파일로 구성된 단일-리소스본문은 Transfer-Encoding이 chunked로 설정되어있으며, 파일은 chunk로 나뉘어 인코딩 되어 있다.
    • Multiple-resource bodies(다중-리소스 본문)
      • 서로 다른 정보를 담고 있는 body

Stateless

  • 상태를 가지지 않는다는 뜻.
  • HTTP로 클라이언트와 서버가 통신을 주고 받는 과정에서, HTTP가 클라이언트나 서버의 상태를 확인하지 않는다.
  • 사용자는 쇼핑몰에 로그인하거나 상품을 클릭해서 상세화면으로 이동하고, 상품을 장바구니에 담거나 로그아웃을 할 수 있다.
  • 클라이언트에서 발생한 이런 모든 상태를 HTTP 통신이 추적하지 않는다.
  • 만약 쇼핑몰에서 장바구니 버튼을 눌렀을 때, 담긴 상품 정보(상태)를 저장해둬야한다. 그러나 HTTP는 통신 규약일 뿐이므로 , 상태를 저장하지 않는다.
    • 따라서 필요에 따라 다른 방법 (쿠키-세션, API등)을 통하여 상태를 확인할 수 있다.(섹션3에서 디테일하게 다룰예정)
  • 지금은 Stateless이 HTTP의 큰 특징이라고 기억하면 된다.

HTTP Request

A fundamental part of understanding restful APIs is understanding the components that make up the client-server flow of HTTP.HTTP can be described as pull protocol.Communication is always initiated by the client sending an HTTP request to the server.In turn, the server responds with a response message.These messages are just bodies of text that the machines can later interpret into actions, images, and even multimedia content. Let's briefly discuss some of the major components of HTTP requests and responses, starting with requests. Every HTTP message consist of a message header, and an optional message body. These two entities are separated by a space, like in the diagram here. In an HTTP request, the first line of the header is called the request line. The request line contains the HTTP verb, the URI , or Uniform Resource Identifier, and the HTTP version number. Take a look at these examples of request lines.

  • GET(verb) /home.html(URI) HTTP/1.1 (version)
  • POST /index.html HTTP/1.1
  • DELETE / query.html HTTP/1.1
    We see the verb here, the resource we want to access via the URI here, and the version of HTTP we are using at the end.
    After the request line we have the optional request headers. These are perimeters that can be used to describe specific properties about a request. Request headers appear in name value pairs. Multiple values can be separated by commas, like so. A blank line separates the header and body of an HTTP request.
    In the body, we can add any other information about the request that we want to send along to the server. An example of a complete HTTP request message is shown here.

HTTP Responses

When a server receives an HTTP request it returns a response message to the client.
This response can contain the information requested or error message if there was one. Similarly to the HTTP request message, the response consists of a message header and optional body. The first line of the header is called the Status Line. Followed by optional response headers. The status line contains the HTTP version, status code, and a reason phrase that explains the status code in English.
Here are some common status codes and reason phrases.

  • "200 OK"
  • "404 Not Found"
  • "403 Forbidden"
  • "500 Internal Server Error"
    The optional response headers take the form of name value pairs, similarly to their request header conterparts. The response message body contains the data that the client requested. If the client asked for a web page, a sample response might look something like this. When you search the web, your web browser takes care of creating HTTP requests and rendering responses on to your screen.
    But as an API developer, there will be times when you have to create and dissect these messages yourself.

Must know concepts

https://developer.mozilla.org/ko/docs/Web/HTTP/Methods

https://developer.mozilla.org/ko/docs/Web/HTTP/Messages

https://developer.mozilla.org/ko/docs/Web/HTTP/Status

profile
블록체인 개발자의 꿈을 위하여

0개의 댓글