[Flutter] http, https

2024. 1. 20. 17:55dev/flutter

728x90
반응형

HTTP : Hyper Text Transfer Protocol

 

http://www.domain.com:80/index/other/page?x=a&y=b 

http

: protocol

 

www.domain.com  

: host

 

80

: port number

http = 80

https  = 443

ftp = 20, 21

 

index/other/page

: resource path

 

?x=a&y=b

: query

 

 

REST API

(Respresentational State Transfer)

we use this communicate client and server.

GET, POST, PUT, DELETE

 

pub add

flutter pub add http

 

import 

import 'package:http/http.dart';

 

use

void demo() async {
  try {
    final url = Uri.parse("https://exampe.com/info");
    http.Response response = await http.get(url);

    debugPrint('...response:${response.body}');

    if (response.statusCode == 200) {
      final data = jsonDecode(response.body);
      debugPrint('response .. 200.. decode.. data:$data');
      // dataType:_Map<String, dynamic>
      debugPrint('response .. 200.. decode.. dataType:${data.runtimeType}');
      this.data = data.toString();
    }

  } catch (e) {
    throw Exception();
  }
}
I/flutter (13374): ...response:{"login":"0","mem_seq":"","mem_type1":"","mem_type2":"","mem_id":"","mem_name":"","mem_email":""}
I/flutter (13374): response .. 200.. decode.. data:{login: 0, mem_seq: , mem_type1: , mem_type2: , mem_id: , mem_name: , mem_email: }
I/flutter (13374): response .. 200.. decode.. dataType:_Map<String, dynamic>

 

 

url : https://www.googleapis.com/books/v1/volumes?q=http

void exam() async {
  var url = Uri.https('www.googleapis.com', '/books/v1/volumes', {'q': '{http}'});

  // Await the http get response, then decode the json-formatted response.
  var response = await http.get(url);
  if (response.statusCode == 200) {
    var jsonResponse = jsonDecode(response.body) as Map<String, dynamic>;
    var itemCount = jsonResponse['totalItems'];
    print('Number of books about http: $itemCount.');
  } else {
    print('Request failed with status: ${response.statusCode}.');
  }
}

 

 

localhost에 값을 전달할 때,

http://127.0.0.1:8080/api/

  var client = http.Client();
  try {
    String name = editingController.text;
    var response = await client.get(Uri.parse("http://127.0.0.1:8080/api/$name"));
    // Log.d("response:$response");
  } catch (e, stackTrace) {
    // Log.w("$stackTrace");
  } finally {
    client.close();
  }
728x90
반응형