How to extract header values from http response? - flutter

I am using http post to send some information and get back the response.
final response = await http.post(
Uri.parse(
"some url"
),
headers: <String, String>{
'email': email,
'callbacktoken': callbacktoken
},
);
When I run this, my execution gets stuck at this codeblock ( I tried putting a print statement in the next line) when the response coming from the backend has header values, however if I send the response with no header from the backend (I am using django at the backend) then the my program runs with no issue.
So my question is how to handle responses with headers and how to extract them?

After a little researching I finally found the issue. My custom header name had space in it "New user" because of which http was not able to parse it. After changing the name to "newuser" everything is working fine.

Related

Uploading file to S3 in Flutter Web (with link from backend)

I'm trying to upload a file to S3 picked with the filepicker package in flutter web. The backend provides me the link to upload the file, so in theory all I need to do is a PUT request to said link. The problem I'm having is (I think) properly sending the file in the body of the request, because if I upload the file directly to S3 with postman on the provided link, it works.
The code below is what I've been working on, after several iterations. I've tried forming the file with http.MultipartFile.fromBytes but the result is the same. I've also tried to send the request with a normal http.put request, and the error there is when I put a Multipart File in the body, if I try to json.encode, I get an error that it wasn't successful, if I don't encode it, it also gives a type error.
This current code is giving and XMLHttpRequest error, which from what I understand is probably due to a CORS error, the thing is I don't understand how that could be. Any input is appreciated!
Here is the code for uploading the image to the link provided by the backend:
Map<String, String> customHeaders2 = {
"x-amz-server-side-encryption-customer-key":
"",
"x-amz-server-side-encryption-customer-algorithm": "AES256",
"x-amz-server-side-encryption-customer-key-MD5":
"",
"Content-Type": "image/png",
"Accept-Encoding": "gzip, deflate, br",
"Connection": "keep-alive",
"Accept": "*/*",
};
final request = http.MultipartRequest(
'PUT',
//body of the response from request to the backend for the link
Uri.parse(jsonDecode(response.body)["data"]["data"]),
);
request.headers.addAll(customHeaders2);
request.files.add(
http.MultipartFile(
'file',
http.ByteStream.fromBytes(file.bytes!),
file.bytes!.length,
filename: file.name,
//contentType: MediaType('application', 'octet-stream'),
),
);
await request.send().then((value) => print(value.statusCode));
Thanks!

How to send JWT token in flutter in a request header?

I'm trying to send a request to a server that requires a parameter called 'fid' sent in the header for autherization.
Here's what you can help me with.
Payload to be sent in the header 👇
{ "fid" : "Some alphaNum value", "type": "some type string" }
I would like to know how to use jwt encoding in flutter and how to use that in the header of a request to encode and send this payload across to the server for autherization. I'm planning to use HS256 algo for encoding. Since I'm new to the concept of Jwt, there might be errors in the way I asked this question. Please share your thoughts. I would also like to know how to use the secret key too -- like how to generate the key, and where in the request to send this.
Request 👇
fetchData({required String type, required String fid, String url}) async{
<How to get the json web token>
http.get(url, header : <What do I send here>);
}
you can use http or Dio package for calling API requests in flutter,
you can set headers as follows,
https://pub.dev/packages/dio
https://pub.dev/packages/http
final response = http.get(url,
headers: {HttpHeaders.contentTypeHeader: "application/json", HttpHeaders.authorizationHeader: "Bearer $token"});

Getting 400 bad request in Axios but in Postman status 200

I'm trying to request a Power BI API using axios.
var configReportInfos = {
method: 'get',
url: `https://api.powerbi.com/v1.0/myorg/groups/${process.env.GROUP_ID}/reports/${process.env.DASHBOARD_ID}`,
headers: {
'Content-Type': 'multipart/form-data',
'Authorization': 'Bearer ' + tokenResponse.accessToken
},
data: {}
};
let reportinfos
try {
reportinfos = await axios(configReportInfos)
tokenResponse['reportInfos'] = reportinfos
}
catch (error) {
console.log(error);
};
Actually I'm getting this error
Request failed with status code 400"
But strangely in Postman I'm getting 200 status.
I'm using same token.
I had the same problem. When l switched content-type in my app to application.json everything worked.
I faced the same issue (not in Axios) and struggled for a few hours.
I was able to make the API call from postman but from my java code I was getting a 400.
Turns out, this was a content issue. My request body had some Cyrillic content and it needed to be encoded before sending.
Postman was doing it by default and hence the requests were going through and responding with 200
I recommend to check your Request Header options in most cases some option is configured wrong.
In your case content-type seems wrong, did you try application/json in both calls.
To configure properly you can check the documentation
Content Type Configuration

Flutter http_auth headers contain "carrier return" and "new line" characters (\r\n)

I am currently experimenting with flutter and tried to use http package. When I request a resource, which requires an authorization header (Authorization: Basic ) I create my request as follows:
import 'package:http/http.dart' as http;
void request() {
http.get('http://<my_url>', headers: {'Authorization': 'Basic <hash>'}).then( (resp) {
print('response status: ${resp.statusCode} ${resp.reasonPhrase}');
}
}
While executing this request, I was watching the request sent over Wireshark and noticed, that it contains carrier-return (\r) and new-line (\n) characters at the end:
Snapshot of Wireshark
After invoking my request function, I get a 401 Unauthorized message in my print statement. When I invoke the same request in Postman, everything is fine.
I assume, that my authentication failed, because of these characters (\r\n) at the end of each header entry. Can anyone help me with it or am I doing something wrong?
PS.: I have also tried the http_auth package but it also failed.
import 'package:http_auth/http_auth.dart' as http_auth;
void request(String user, String password) {
http_auth.BasicAuthClient(user, password).get('http://<my_url>', headers: {'Authorization': 'Basic <hash>'}).then( (resp) {
print('response status: ${resp.statusCode} ${resp.reasonPhrase}');
}
}
Those \r\n characters are meant to be there. They are the line separators between the headers. If you packet capture the wire bytes from curl --user foo:bar www.dart.dev you will see exactly the same thing.
You will notice that Dart has lower-cased the header name to authorization as is perfectly valid per the RFC. However, this sometimes catches out some servers that (incorrectly) treat the header names case sensitively.
Try your postman again (or a curl with a manually-created, lower-case header) with authorization. If the server doesn't accept that, contact the server maintainer.

POST image to web service with Flutter

I am currently using Flutter and Dart to try to send an image to a web service, after which I wait for a JSON response. The below links show the Postman request that I am trying to mimic.
An image of Postman with the headers required
An image of Postman with the body
I think the issue I am having is either not setting the headers of my request correctly, or not encoding the image correctly.
Currently I am getting a HTTP 400 error.
I have tried following these suggested solutions on StackOverflow but have been getting the HTTP 400 error.
Any help would be much appreciated!
Try this. I'd suggest creating yourself a plain Dart project, if you haven't already. This way you can test things without the need of the phone emulator, etc.
main() async {
http.MultipartRequest request =
new http.MultipartRequest('POST', Uri.parse(url));
request.headers['Prediction-Key'] = '3f4a......'; // todo - insert real value
request.files.add(
new http.MultipartFile.fromBytes(
'image',
bytes,
filename: 'somefile', // optional
contentType: new MediaType('image', 'jpeg'),
),
);
http.StreamedResponse r = await request.send();
print(r.statusCode);
}
If the file is on disk, not in memory, then use the fromPath named constructor instead. Experiment with different media types. I've used image/jpeg, but you could try application/octet-stream.
As an aside, in your first screenshot you show a content type, but Postman ignores this as the overall content type is overridden by multipart-form. Uncheck that row in Postman to prove this.
There was another question recently on SO, where the server was incorrectly expecting headers to be case sensitive. In postman, try again with lowercase prediction-key to prove that the server doesn't mind lowercase headers (which is what Dart uses).