Skip to content

Instantly share code, notes, and snippets.

@xcsrz
Last active February 14, 2023 19:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xcsrz/5974d8e47ed004ddcacac47ac215cdbc to your computer and use it in GitHub Desktop.
Save xcsrz/5974d8e47ed004ddcacac47ac215cdbc to your computer and use it in GitHub Desktop.
Posting from Dart to a URL with a redirect: Since Dart's stock http package (and even the dio package) chose to handle redirects differently than basically every other language+package out there and disregard redirect responses returned to a POST request you have to do a little extra work. Worse than anything is every solution I have found was #…
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart';
String url =
"https://script.google.com/macros/s/YOUR_DEPLOYMENT_HASH_HERE/exec";
final data = {
'foo': 456,
'bar': 'that',
'biz': 23,
};
void main(List<String> args) {
postRequestWithRedirect(url, jsonEncode(data)).then((r) {
print('code: ' + r.statusCode.toString());
print('body: ' + r.responseBody.toString());
});
}
class postRequestWithRedirectResult {
num? statusCode;
String? responseBody;
}
Future<postRequestWithRedirectResult> postRequestWithRedirect(
String url,
String body,
) async {
var httpclient = HttpClient();
HttpClientRequest request;
HttpClientResponse response;
postRequestWithRedirectResult result = postRequestWithRedirectResult();
try {
request = await httpclient.postUrl(Uri.parse(url));
request.headers.contentLength = body.length;
request.write(body);
response = await request.close();
final location = response.headers.value(HttpHeaders.locationHeader);
if (response.statusCode == 302 && location != null) {
request = await httpclient.getUrl(Uri.parse(location));
response = await request.close();
result.statusCode = response.statusCode;
result.responseBody = await response.transform(utf8.decoder).join();
} else {
result.statusCode = response.statusCode;
result.responseBody = await response.transform(utf8.decoder).join();
}
} finally {
httpclient.close(force: true);
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment