below is the code that I tried but it didn't work, how to insert header on MultipartRequest?
var id = prefs.getInt('id');
var token = prefs.getString('accessToken');
var uri = Uri.parse('https://url.com/submit/$id');
var headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer $token'
};
var request = http.MultipartRequest('POST', uri);
request.files.add(
await http.MultipartFile.fromPath('file', _files.first.path.toString()),
);
var response = await request.send();
Headers is a map attribute of the request object, you can simply use map methods on it:
request.headers.addAll(headers)
Related
This is my code. The goal is to get the link with file id.
// body parameter
Map<String, dynamic> body = {'file_id': 123};
String jsonBody = json.encode(body);
// response request
var download_response = await http.post(
Uri.parse('https://api.opensubtitles.com/api/v1/download'),
headers: {
'Content-Type': 'application/json',
'Api-Key': 'yCTZwGASncUthpMkMkbQDjcUdrrM2r8v'
},
body: jsonBody,
);
// print
debugPrint(download_response.body.toString());
I think I should be getting a JSON data response which I'm getting properly with postman but in flutter I'm getting empty response.
Things I tried:
encoding the body with jsonencode
correct syntax formatting
writing the body in plain json string
var headers = {
'Api-Key': 'yCTZwGASncUthpMkMkbQDjcUdrrM2r8v',
'Content-Type': 'application/json'
};
var request = http.MultipartRequest('POST', Uri.parse('https://api.opensubtitles.com/api/v1/download'));
request.fields.addAll({
'file_id': '123'
});
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
}
else {
print(response.reasonPhrase);
}
I wanted to send raw data in flutter http and the data doesn't look like JSON
Here's how I done that in Postman
and tried this in flutter using http,
Response res = await post(
Uri.parse(baseUrl + endPoint),
headers: {'Client-ID': clientId, 'Authorization': 'Bearer $accessToken'},
body: jsonEncode('fields *'),
);
and got this in console,
Error: XMLHttpRequest error.
Add it as this
var headers = {
'Accept': 'application/json',
'Content-Type': 'text/plain',
};
var request = http.Request('POST', Uri.parse('Your url'));
request.body = '''fields *''';
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
}
else {
print(response.reasonPhrase);
}
Or you can easily see it being implemented in Postman's code request to the right just select the code icon and choose http-Dart
hello I'm trying to do a post request with JSON and file together how should it be
static Future postApost(String posttitle,image,String value,token) async {
var data = {'posttitle': posttitle, 'post': image.readAsBytes(),'category': value};
await http.post("https://lighte.org/public/api/newpost",headers: {
'Authorization': 'bearer $token',
},body: data).catchError((error) {
print(error.toString());
});
}
static Future postApost(String posttitle,image,String value,token) async {
var request = http.MultipartRequest(
'POST', Uri.parse("https://lighte.org/public/api/newpost"));
//**fromPath()** method is used when you are sending an image from a specific path,
//inCase of String byte Images you have to use the preferred method in MultipartFile class
await http.MultipartFile.fromPath(
'image',
image.path,//use can pass file path here
filename: 'image_name.jpg',
);
request.fields['posttitle'] = posttitle;
request.fields['category'] = value;
request.headers["Authorization"] = 'bearer $token';
}
uploadUserImg (
String filename, String url, File img, String token
) async {
//URI with type of request (POST or GET ...) ---------------
var request = http.MultipartRequest('POST', Uri.parse(url));
//Header type with access token ------------------------
request.headers.addAll({
"Content-Type": "application/json",
'Authorization': 'Bearer $token ',
});
//adding body parameter for request -----------------------
// you can remove this it will not affect the code
request.fields.addAll({
'phone_number': '+201097081508'
});
// adding File image -------------------------------
request.files.add(
http.MultipartFile.fromBytes('image_endpoint', img.readAsBytesSync(),
filename: filename));
//send request + listing to its response
request.send().then(
(response) {
//parsing the response to print it
response. stream.transform(utf8.decoder).listen(
(responseString) {
print(responseString);
});
}
I want to sent my auth-key in headers using http package but unfortunately its not working kindly help me .
var url = "https://paysafemoney.com/psmApi/Psm/userDashboard";
var response = await http.post(
url,
headers: {
"auth-key": LoginConfirmActivity.authKey,
},
body: sendLoginData,
);
print("Response = ${response.body}");
You can do like this
var fullUrl = '$stripeBaseUrl$customerId/sources?source=$cardToken';
var header = {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': stripeKey,
};
final response = await client.post(fullUrl, headers: header);
I have faced the issue like get access token in PayPal using flutter
How can I solve the issue?
try this function. hope it can work.
Future makePost() async {
String username = "*************";
String password = "*************";
var bytes = utf8.encode("$username:$password");
var credentials = base64.encode(bytes);
Map token = {
'grant_type': 'client_credentials'
};
var headers = {
"Accept": "application/json",
'Accept-Language': 'en_US',
"Authorization": "Basic $credentials"
};
var url = "https://api.sandbox.paypal.com/v1/oauth2/token";
var requestBody = token;
http.Response response = await http.post(url, body: requestBody, headers: headers);
var responseJson = json.decode(response.body);
return responseJson;
}