How to make a proper http request? - flutter

I can't seem to make a proper http request with my code. Whenever I run the following code,
var url = Uri.https('datamall2.mytransport.sg', '/ltaodataservice/BusArrivalv2?BusStopCode=', {'BusStopCode': busStopCode});
final response = await http.get(
url,
headers: <String, String>{
'Content-Type': 'application/json',
'AccountKey': accountKey,
},
);
I get the following error
I/flutter (24816): SocketException: OS Error: Connection refused, errno = 111, address = datamall2.mytransport.sg
This is the http request I'm trying to make
http://datamall2.mytransport.sg/ltaodataservice/BusArrivalv2?BusStopCode=busStopCode (busStopCode is a 5 digit number)

The wrong protocol is being used.
You've requested httpS.
The server is only responding to http.
You could try something simpler:
String url = 'http://datamall2.mytransport.sg/ltaodataservice/BusArrivalv2?$busStopCode';
final response = await http.get(
url,
headers: <String, String>{
'Content-Type': 'application/json',
'AccountKey': accountKey,
},
);

You should change your url variable to:
var url = Uri.http('datamall2.mytransport.sg', '/ltaodataservice/BusArrivalv2', {'BusStopCode': busStopCode});

Related

Flutter Boundary Regex not accepted

I have to make a post call to upload a image. Getting an error due to the boundary values in the header. (Regex not matched)
var requestUrl = API_URL;
// INITIALIZE MULTIPART REQUEST
http.MultipartRequest request;
// PREPARE HEADER VALUES
request = new http.MultipartRequest("POST", Uri.parse(requestUrl));
Map<String, String> headers = {
'Content-Type': 'multipart/form-data',
'Accept': 'multipart/form-data',
'Authorization': 'Bearer '+accessToken,};
request.headers.addAll(headers);
// DECLARE FILE NAME WEB
String imageType = "image." + this.xfile!.mimeType.toString().split('/').last;
// ADD TO REQUEST
request.files.add(http.MultipartFile.fromBytes('image', await this.xfile!.readAsBytes(), filename:imageType ));
// SEND REQUEST
http.StreamedResponse responseAttachmentSTR = await request.send();
I deployed the codes to the server. Apparently this causes a 403 Forbidden error, when I try to upload an image.
Through debugging, it was because of the regex in the Header (Boundary):
boundary=dart-http-boundary-poYEiL0Ungmxkla.2lkZeC6Mub.-Fupw5T_MmJpxColFVjXf-qr
What can I do about this?

Api Authorization working in postman but not working in flutter

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

Flutter HTTP calls using authorization fails but works in postman

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);

http.post return 307 error code in flutter

I am using http client for flutter network call.
My request working on postman getting response properly,
But while trying with http.post it returns error code 307-Temporary Redirect,
Method Body:
static Future<http.Response> httpPost(
Map postParam, String serviceURL) async {
Map tempParam = {"id": "username", "pwd": "password"};
var param = json.encode(tempParam);
serviceURL = "http:xxxx/Login/Login";
// temp check
Map<String, String> headers = {
'Content-Type': 'application/json',
'cache-control': 'no-cache',
};
await http.post(serviceURL, headers: headers, body: param).then((response) {
return response;
});
}
Also, the same code returns a proper response to other requests and URLs.
First I trying with chopper client but had same issue.
I am unable to detect that issue from my end of from server-side.
Any help/hint will be helpful
Try to put a slash / at the end of the serviceUrl. So, serviceUrl is serviceURL = "http:xxxx/Login/Login/" instead of serviceURL = "http:xxxx/Login/Login".
This works for me.
You need to find a way to follow redirect.
Maybe postman is doing that.
Read this >>
https://api.flutter.dev/flutter/dart-io/HttpClientRequest/followRedirects.html
Can you try with using get instead of post? At least to try and see what happend
In the documentation said:
Automatic redirect will only happen for "GET" and "HEAD" requests
only for the status codes
HttpStatus.movedPermanently (301),
HttpStatus.found (302),
HttpStatus.movedTemporarily (302, alias for HttpStatus.found),
HttpStatus.seeOther (303),
HttpStatus.temporaryRedirect (307)
keeping https instead of http in the URL it is helping me.
#Abel's answer above is correct but I had to switch from using:
Uri url = Uri.https(defaultUri, path);
to
Uri url = Uri.parse('https://todo-fastapi-flutter.herokuapp.com/plan/');
to get that last / after plan.
The first way kept dropping it so I was getting 307 errors.
flutter.dev shows a full example:
Future<http.Response> createAlbum(String title) {
return http.post(
Uri.parse('https://jsonplaceholder.typicode.com/albums'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'title': title,
}),
);
}
here: https://flutter.dev/docs/cookbook/networking/send-data#2-sending-data-to-server
For Dio Http Client, use Dio Option follow redirect as True
getDioOption(){
return BaseOptions(connectTimeout: 30, receiveTimeout: 30,
followRedirects: true);
}

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.