Last active
February 14, 2023 19:31
-
-
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 #…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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