I am using Flutter 1.20.4, http 0.12.2 package and I am having an issue where my HTTP calls are successful in Postman but fail in a flutter. I came across a number of articles talking about issue with lower case HTTP headers and some older servers. I don't have that issue as I have tested postman with lower case. I have checked my bearer token on jwt.io and issuer matches the domain I am using. Any call made from flutter that uses authorization will return as "not authenticated" so it would come up with HTTP 302 (redirect to login by identity provider). Any ideas?
My code looks like this:
import 'package:http/http.dart' as http;
...
var getProfileUrl = _identityApi + '/api/profile/get'; // TODO: CHANGE THIS
var accessToken = await _secureStorage.read(key: 'bearerToken');
var response = await http.get(getProfileUrl, headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $accessToken'
});
POSTMAN:
FLUTTER:
try this
import 'package:http/http.dart' as http;
...
Map<String,String> _headers={
'content-type': 'application/json',
'accept: 'application/json',
'authorization': 'Bearer $accessToken'
};
var getProfileUrl = _identityApi + '/api/profile/get'; // TODO: CHANGE THIS
var accessToken = await _secureStorage.read(key: 'bearerToken');
var response = await http.get(getProfileUrl, headers: _headers);
Related
I'm trying to upload a binary file to Dropbox using https://github.com/dart-lang/http. Following https://dropbox.github.io/dropbox-api-v2-explorer/#files_upload, my code is:
import 'package:http/http.dart' as http;
Map<String,String> headers = {
'Authorization': 'Bearer MY_TOKEN',
'Content-type': 'application/octet-stream',
'Dropbox-API-Arg': '{"path": "/file", "mode": "overwrite"}',
};
final resp = await http.post(
Uri.parse("https://content.dropboxapi.com/2/files/upload"),
body: "--data-binary #\'/my/binary/file\'",
headers: headers);
file gets uploaded, but unfortunately this only contains the text --data-binary #'/my/binary/file' (i.e. not the actual file).
Am I missing something/doing something incorrectly?
Sending binary data directly as the body worked:
import 'package:http/http.dart' as http;
final file = File('/my/binary/file');
Uint8List data = await file.readAsBytes();
Map<String,String> headers = {
'Authorization': 'Bearer MY_TOKEN',
'Content-type': 'application/octet-stream',
'Dropbox-API-Arg': '{"path": "/file", "mode": "overwrite"}',
};
final resp = await http.post(
Uri.parse("https://content.dropboxapi.com/2/files/upload"),
body: data,
headers: headers);
Since you pass
body: "--data-binary #\'/my/binary/file\'",
as the body of your POST request, exactly this is the data to get send to the server. The body is raw data, that just gets passed along to the server and in no way interpreted by dart.
Have a look at Dart's MultipartRequest. Or for general information:SO on multipart requests.
I created an api with authorization, It is working correctly in postman but but i am not able to use authorization in flutter, I am getting Statuscode: 401(unauthorized) in flutter but in postman i am getting statuscode: 200(success). Here is my Code:
sharedPreferences = await SharedPreferences.getInstance();
String Authorization = sharedPreferences.getString("token");
var data = await http.get("http://10.148.7.58/Election/api/TblDatas",
headers: <String, String>{'Authorization': '$Authorization',}
);
//Also tried these
//headers: {'Content-Type': 'application/json', 'Accept': 'application/json', 'Authorization': '$Authorization',}
//headers: {HttpHeaders.contentTypeHeader: "application/json", HttpHeaders.authorizationHeader: "$Authorization"}
print('status code is' + (data.statusCode).toString());
headers: <String, String>{
'Content-Type': 'application/json', //add context-type
'Accept': 'application/json',//add accept
'Authorization': 'Bearer $token',
}
Make sure that your server accepts lower case header names - in this case authorization, as Dart will lower case them. This fools some servers that aren't RFC compliant
Im trying to make a http-request to Filemaker with Flutter(package:http/http.dart)
I can get the token normally, but if i try the make an _find request to Filemaker it always get's rejected(400 Bad Request) without any message.
In Postman I can do the exact same request without issue!
var body = { "query":[{
"loginName": "==testUser#test.com"
}]};
Response response = await post(url,
headers: {
HttpHeaders.authorizationHeader: 'Bearer $token',
HttpHeaders.contentTypeHeader: 'application/json'},
body: json.encode(body));
Found it:
Dart http adds: content-type: application/json; charset=utf-8
And Filemaker rejects this..
But now is the question why does Filemaker API rejects such an API Call?
SOLVED.
I was able to access one user in a FileMaker layout using Dio.
Dio dio = Dio();
dio.options.headers['content-Type'] = 'application/json';
dio.options.headers["authorization"] = "Bearer ${token}";
Response recordResponse;
recordResponse = await dio.post(
findUrl,
options: Options(followRedirects: false, validateStatus: (status)
{return status < 500;}),
data: { "query":
[{
"username": "=Jake",
"password": "=password"
}]
}
);
I am making a flutter application, and i have written a server in django. When i send a token to my server for authentication then my server sends me an error of undefined token. Without token all requests works fine, but when i add a token then it gives me an error
{detail: Authentication credentials were not provided.}
But When i add token in modheader, my server works fine
Authorization: Token bff0e7675d6d80bd692f1be811da63e4182e4a5f
This is my flutter code
const url = 'MY_API_URL';
var authorization = 'Token bff0e7675d6d80bd692f1be811da63e4182e4a5f';
final response = await http.get(
url,
headers: {
'Content-Type': 'application/json',
'Authorization': authorization,
}
);
final responseData = json.decode(response.body);
print('responseData');
print(responseData);
try this:
Map<String, String> headers = {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Token bff0e7675d6d80bd692f1be811da63e4182e4a5f'
};
& use them in request
final response = await http.get(
url,
headers: headers,
);
As I don't know to work on your API so I can't tell you the exact answer.
Check that, Is your backend taking authorization by header or body or
I'll suggest you first make authorization by tools like postman then
if that succeeds then try to implement that in your app.
I was trying to make a call to a REST service using the Dio plugin, but kept getting HTTP 400 response code. I thought I was doing everything right by setting the content type and response type options to JSON:
Response response = await Dio().get(
'https://api.example.com/v1/products/$productId',
queryParameters: {},
options: Options(
contentType: ContentType.json,
responseType: ResponseType.json,
headers: {'Authorization': 'Bearer $MY_API_KEY'}
),
);
However, it turns out that I needed to add a Content-Type header as well:
headers: {'Authorization': 'Bearer $MY_API_KEY'}, 'Content-Type': 'application/json' };
So now I'm confused - what exactly does the contentType option do? I thought it was analogous to setting the Content-Type header manually?
I've tried this locally using dio: ^3.0.10 and it seems that ContentType.json is an invalid value for contentType.
Digging through the documentation for dio, Headers.jsonContentType should be used.