DEV Community

BC
BC

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("httpbin.org", 80);
  socket.writeln("GET /get HTTP/1.1");
  socket.writeln("Host:httpbin.org");
  socket.writeln("Connection:close");
  socket.writeln();
  // 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();
  print(resp);
}
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": "httpbin.org",
    "X-Amzn-Trace-Id": "Root=1-61bd5fa4-17f8006279006770433cc1ec"
  },
  "origin": "67.83.127.85",
  "url": "http://httpbin.org/get"
}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
krtirtho profile image
Kingkor Roy Tirtho

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