DEV Community


Posted on

Use raw socket in Dart

In the previous post we showed how to use the dio lib in Dart to send http request, this one we will show an example of using the raw Socket object to send a http GET request.

import 'dart:convert';
import 'dart:io';

void main() async {
  var socket = await Socket.connect("", 80);
  socket.writeln("GET /get HTTP/1.1");
  // send request
  await socket.flush();
  // now get response content and decode it with utf-8
  String resp = await utf8.decoder.bind(socket).join();
  await socket.close();
Enter fullscreen mode Exit fullscreen mode

Run it:

$ dart main.dart
HTTP/1.1 200 OK
Date: Sat, 18 Dec 2021 04:12:20 GMT
Content-Type: application/json
Content-Length: 197
Connection: close
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true

  "args": {},
  "headers": {
    "Host": "",
    "X-Amzn-Trace-Id": "Root=1-61bd5fa4-17f8006279006770433cc1ec"
  "origin": "",
  "url": ""
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

krtirtho profile image
Kingkor Roy Tirtho

YOU're awesome bro. I could hug you! Saved my 8 hours