Dio options.contentType vs header "Content-Type" - rest

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.

Related

Post Files to ASPNetCore API IFormFile Type

I want to send data with files to AspNetCore api that receive files type IFormFile I tried this
Dio dioFile = Dio(
BaseOptions(
baseUrl: baseUrl,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ${APIVariables.token}',
},
),
);
dioFile.post(
url,
data: {
"id": complaint.id,
"title": complaint.title,
"files": complaint.files
.map((file) => base64Encode(file.readAsBytesSync()))
.toList(),
};
);
but it shows dio error: DioError [DioErrorType.response]: Http status error [400].
How can I solve that and is there another better method to do that?
And if I want to send files using MultipartFile how can I do that and what api specialist should do to handle my post?
If you want to send the image file then,
It should look like this.
String fileName = imageFile.path.split('/').last;
FormData formData = FormData.fromMap({
"image-param-name": await MultipartFile.fromFile(
imageFile.path,
filename: fileName,
contentType: new MediaType("image", "jpeg"), //important
),
});
If without this line.
contentType: new MediaType("image", "jpeg")
Maybe it will cause an error: DioError [DioErrorType.RESPONSE]: Http status error [400] Exception
You must confirm the correct contentType to work it as expected
And get MediaType in this package: http_parser

How to set `Content-Type` in headers in Axios?

I'm having trouble setting the Content-Type header in axios.
Here's my code:
axios({
url: fetchUrl,
data: JSON.stringify(fetchOptions.body),
method: 'POST',
headers: {
'Content-Type': 'application/vnd.api+json',
Accept: 'application/vnd.api+json',
},
})
And here's the request headers:
Accept is set correctly but Content-Type is not. (Confirmed by removing Accept in my code, in which case the request header reverts to json isntead of vnd.api+json.)
When I change Content-Type to ContentType, then I see ContentType in the Response headers, so the problem is specifically with Content-Type.
It turns out that this error was the result of having an empty data; the property was called data, but I mistakenly called body:
axios({
url: fetchUrl,
data: JSON.stringify(fetchOptions.data),
method: 'POST',
headers: {
'Content-Type': 'application/vnd.api+json',
Accept: 'application/vnd.api+json',
},
})

How to send a token in a request in flutter?

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.

Flutter: Http Request has no body

I am trying to send a http request using the http plugin on version ^0.12.0+4 (the latest one).
http.Response response = await http.post(
http://localhost:8085,
body: jsonEncode({"test": "test"}),
headers: {
"accept": "application/json",
"content-type": "application/json"
},
);
I have a SpringBoot backend running which stated, that the request body is empty. Debug attempts with Postman worked fine.
I tried the Dio package as well with the same result.

Ionic Changes Content-Type

Ok I have to make a simple GET request that work in Postman but not in the Ionic code. I have determined that the reason is that the API treats incoming requests differently based on Content-Type. application/json works text doesn't.
headers: {
"Content-Type": 'application/json; charset=UTF-8',
"Accept": 'application/json; charset=UTF-8'
},
As you can see I'm setting the header to try to force application/json but when I sniff the request it has changed to text/html somehow. How do I force Ionic to take my Content-Type as definitive?
I managed to get it to work with the following headers
var headers = {
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Methods" : "POST, GET, OPTIONS, PUT",
"Content-Type": "application/json",
"Accept": "application/json"
};