问题
I'm trying to read reponse from HTTP in flutter but I didnt read. I posted the request. Can anyone know, what is wrong ?
final http.Client client;
Future<http.Response> post(
Uri uri, {
Map<String, dynamic> postParams,
String accessToken,
}) async {
log.info(uri.toString());
log.info('postParams: ${postParams?.toString()}');
///Encode map to bytes
String jsonString = json.encode(postParams);
List<int> bodyBytes = utf8.encode(jsonString);
Map headers = {
HttpHeaders.contentTypeHeader: 'application/json; charset=utf-8',
};
final response = await client
.post(
uri,
body: bodyBytes,
headers: headers,
)
.timeout(Duration(seconds: 120));
}
回答1:
You can achieve this functionality as follow
1.install http
package and import it as follow
import 'package:http/http.dart' as http;
Create an instance of
http
orhttp.Client
as you didfinal http.Client _client = http.Client();
Send the request to server as follow
var url = 'https://example.com/store/.....'; final Map<String, dynamic> data= {"name":"John Doe", "email":"johndoe@email.com"}; final Map<String, String> _headers = { "Content-Type": "application/json", "Accept": "application/json", }; var response = await _client.post(url, body:data, headers:_headers);
Then you can read the response as
if(response.statusCode == 200) { var decoded = json.decode(response.body); print(decoded); // The Rest of code }
来源:https://stackoverflow.com/questions/60409417/how-to-read-http-response-from-flutter