0

Here's the second example given by the http package: https://pub.dev/packages/http

var client = http.Client();
try {
  var uriResponse = await client.post('https://example.com/whatsit/create',
      body: {'name': 'doodle', 'color': 'blue'});
  print(await client.get(uriResponse.bodyFields['uri']));
} finally {
  client.close();
}

I get error: uriResponse.bodyFields['uri'] no such method.

I can see that there's no property named bodyFields in the class Response: https://pub.dev/documentation/http/latest/http/Response-class.html

So how should I use the client.get()?

I checked the docs for the function https://pub.dev/documentation/http/latest/http/get.html and I wrote this:

print(await client.get(uriResponse.request.url, {
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36',
}));

But this also fails with error:

Class 'IOClient' has no instance method 'get' with matching arguments.
E/flutter (19613): Receiver: Instance of 'IOClient'
E/flutter (19613): Tried calling: get(Instance of '_SimpleUri', Instance of '_CompactLinkedHashSet<Map<String, String>>')
E/flutter (19613): Found: get(dynamic, {Map<String, String> headers}) => Future<Response>
Shayan
  • 709
  • 1
  • 15
  • 31
  • 1
    Your `client.get` attempt needs to use `client.get(..., headers: { ... })` because the `headers` parameter is *named*. The issue about the incorrect example is https://github.com/dart-lang/http/issues/173. – jamesdlin Sep 30 '20 at 17:22
  • It fixes the errors thanks, but according to the docs, client.get() should return a instance of the Response class but when I check, it's always empty. Have checked multiple websites including example.com – Shayan Sep 30 '20 at 21:54

2 Answers2

0

write your post as below and print the response separate.

final response = await client.post(
    '*endPoint url*',
    headers: *headers if you have any*,
    body: jsonEncode({'name': 'doodle', 'color': 'blue'}
    ));

print(json.decode((response.body)));

and follow the same structure for the get method as well.

Sajith
  • 713
  • 6
  • 21
  • Same structure for GET, causes error: `Exception has occurred. ClientException (Content size below specified contentLength. 0 bytes written but expected 793.)` – Shayan Sep 30 '20 at 13:37
0
String url = "url";
Response response = await client.get(url);
print('Response status: ${response.statusCode}');
print('Response body: ${json.decode((response.body))}');