1000sj
SJ CODE
1000sj
전체 방문자
오늘
어제
  • 분류 전체보기
    • 알고리즘
    • 네트워크 보안
      • 네트워크
      • 보안
      • CTF
      • Exploit
    • System Programming
      • Operating System
      • Compiler
      • Device Driver
      • Emulator
    • Application Programming
      • Script
      • Android
    • 클라우드 컴퓨팅
      • Cloud Native
      • Public Cloud
      • Infrastructure
      • Database
      • DevOps
    • 트러블슈팅
    • ETC
      • 문화 생활
      • 커뮤니티

인기 글

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
1000sj

SJ CODE

[Flutter] HTTP 통신
Application Programming

[Flutter] HTTP 통신

2021. 9. 7. 10:11

HTTP는 클라이언트와 서버 사이에 이루어지는 요청/응답 프로토콜이다. 예를 들면 클라이언트인 웹브라우저가 HTTP를 통해 서버로부터 웹페이지(HTML)나 image data를 요청하면 서버는 이 요청에 응답하여 필요한 정보를 해당 사용자에게 전달하게 된다.

http 요청/응답 예시

메세지 구문

클라이언트와 서버 사이의 통신은 보통 ASCII코드로 이루어진다. 클라이언트는 서버로 요청메세지를 보내며 서버는 응답메세지를 보낸다.

Request 메세지 문법

  • 요청내용
    • GET /images/logo.gif HTTP/1.1
  • 헤더
    • Accept-Language: en
  • empty line
  • etc

 

HTTP 메소드 RFC 요청에 body가 있음 응답에 body가 있음 Safe 멱등 Cacheable
GET RFC 7231 아니요 예 예 예 예
HEAD RFC 7231 아니요 아니요 예 예 예
POST RFC 7231 예 예 아니요 아니요 예
PUT RFC 7231 예 예 아니요 예 아니요
DELETE RFC 7231 아니요 예 아니요 예 아니요
CONNECT RFC 7231 예 예 아니요 아니요 아니요
OPTIONS RFC 7231 선택 사항 예 예 예 아니요
TRACE RFC 7231 아니요 예 예 예 아니요
PATCH RFC 7231 예 예 아니요 아니요 예
  1. safe: 해당 메서드를 사용한 요청이 서버에 의도된 영향을 미치지 않는 경우 요청 메서드는 안전, 즉 읽기전용
  2. 멱등: 요청 방법이 있는 여러 동일한 요청이 단일 요청과 동일한 의도된 효과를 갖는 경우
  3. cacheable: 요청 방법을 사용하는 요청에 대한 응답을 나중에 재사용할 수 있도록 저장할 수 있는 경우 요청 방법을 캐시 할 수 있다.

 

Response 메세지 문법

  • status line: 프로토콜 버전, 공백, 응답 상태 코드, 공백, 비어있을 수 있는 이유 문구, CRLF로 구성
  • 0개 이상의 response header field: 대소문자를 구분하지 않는 필드 이름, 콜론, 선택적 선행 공백, 필드 값 및 선택적 후행 공백(예: Content-Type: text/html )으로 구성되고 CRLF로 끝남
  • empty line: CRLF로 구성
  • message body(선택)

 

Response 상태코드

1XX 정보제공: 요청을 받았고 진행중
2XX 성공: 요청이 성공적으로 수신되고 수락됨
3XX 리다이렉션: 요청을 완료하기위해 추가조치가 필요
4XX 클라이언트 오류: 요청에 잘못된 구문이 있거나 수행할 수 없음
5XX 서버 오류: 서버가 분명히 유효한 요청을 이행하지 못함

Response 헤더필드(응답헤더필드 종류)
응답 헤더 필드를 통해 서버는 응답 한정자 역할을 하는 추가 정보를 status line 앞으로 전달할 수 있다. 서버에 대한 정보 또는 대상 리소스 또는 관련 리소스에 대한 추가 액세스에 대한 정보를 제공한다. 각 응답 헤더 필드에는 요청 방법 또는 응답 상태 코드의 의미론에 의해 더욱 세분화될 수 있는 정의된 의미가 있다.

 

HTTP 통신 예시(with Flutter)

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(title: 'Flutter Http Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            MaterialButton(onPressed: () => _getRequest(), child: Text("get https")),
            MaterialButton(onPressed: () => _postRequest(), child: Text("post http")),
          ],
        ),
      ),
    );
  }

  void _getRequest() async {
    var url = Uri.parse("https://jsonplaceholder.typicode.com/posts/1");
    http.Response _response = await http.get(url, headers: {"Accept": "application/json"});

    var statusCode = _response.statusCode;
    var _headers = _response.headers;
    var _body = utf8.decode(_response.bodyBytes);

    print("statusCode : $statusCode");
    print("statusHeader : $_headers");
    print("statusBody : $_body");
  }

  _postRequest() async {
        var url = Uri.parse("http://example.com/login");
    http.Response _response = await http.post(
      url, 
      headers: {"Content-Type": "application/x-www-form-urlencoded"},
      body: {
        'userId' : 'user_id_value',
        'userPassword' : 'user_password_value'
      });

    var statusCode = _response.statusCode;
    var _headers = _response.headers;
    var _body = utf8.decode(_response.bodyBytes);

    print("statusCode : $statusCode");
    print("statusHeader : $_headers");
    print("statusBody : $_body");
  }
}

Response

  • https get

  • http post

 

 

 

 

Ref

  • wiki pedia
  • flutter http package

'Application Programming' 카테고리의 다른 글

[Typescript]  (0) 2021.10.15
[Node.js] Modules  (0) 2021.09.20
[Node.js] Node.js 설치  (0) 2021.09.19
[Flutter] 포켓몬도감  (0) 2021.09.06
[Flutter] StatelessWidget  (0) 2021.05.27
    'Application Programming' 카테고리의 다른 글
    • [Node.js] Modules
    • [Node.js] Node.js 설치
    • [Flutter] 포켓몬도감
    • [Flutter] StatelessWidget
    1000sj
    1000sj

    티스토리툴바