Joomshopping to Flutter - flutter

I want get data from Joomshopping to Flutter.
I install joomshopping Rest Api component and create user.
Then in Flutter i code this (site, email, password i use from my site)
class _JoomApiState extends State<JoomApi> {
Future getData() async {
final str = "email:pass";
final bytes = utf8.encode(str);
final base64Str = base64.encode(bytes);
var response = await http.post(
Uri.parse(
'https://site.ru/index.php?option=com_jshopping&controller=addon_api'),
headers: {'Authorization': 'Basic $base64Str'},
body: {},
);
print(response.body);
}
in debug console i see "{"status":"request_error","code":2,"report":"Request error. No section","result":null}".
How get data from Joomshopping to Flutter?

Related

How to make a http post using form data in flutter

I'm trying to do a http post request and I need to specify the body as form-data, because the server don't take the request as raw or params.
here is the code I tried
** Future getApiResponse(url) async {
try {
// fetching data from the url
final response = await http.get(Uri.parse(url));
// checking status codes.
if (response.statusCode == 200 || response.statusCode == 201) {
responseJson = jsonDecode(response.body);
// log('$responseJson');
}
// debugPrint(response.body.toString());
} on SocketException {
throw FetchDataException(message: 'No internet connection');
}
return responseJson;
}
}
but its not working. here is the post man request
enter image description here
its not working on parms. only in body. its because this is in form data I guess.
how do I call form data in flutter using HTTP post?
First of all you can't send request body with GET request (you have to use POST/PUT etc.) and you can use Map for request body as form data because body in http package only has 3 types: String, List or Map. Try like this:
var formDataMap = Map<String, dynamic>();
formDataMap['username'] = 'username';
formDataMap['password'] = 'password';
final response = await http.post(
Uri.parse('http/url/of/your/api'),
body: formDataMap,
);
log(response.body);
For HTTP you can try this way
final uri = 'yourURL';
var map = new Map<String, dynamic>();
map['device-type'] = 'Android';
map['username'] = 'John';
map['password'] = '123456';
http.Response response = await http.post(
uri,
body: map,
);
I have use dio: ^4.0.6 to create FormData and API Calling.
//Create Formdata
formData = FormData.fromMap({
"username" : "John",
"password" : "123456",
"device-type" : "Android"
});
//API Call
final response = await (_dio.post(
yourURL,
data: formData,
cancelToken: cancelToken ?? _cancelToken,
options: options,
))

why flutter often occur return connection closed before full header was received

I use HTTP for connection to API, and I have tried some flutter sdk like 2.5, 2.10.5, 3 but still have same issue often occur return connection closed before full header was received. and it's can occur in random api and all apps I build in flutter.
it's example of my code
Future<dynamic> getGoodSolution() async {
final url = Uri.parse('$url');
final headers = {HttpHeaders.contentTypeHeader: 'application/json', HttpHeaders.authorizationHeader: 'Bearer mytoken123'};
var map = <String, dynamic>{};
map["xxx"] = "123";
// print(headers);
try {
final response = await client.post(url, headers: headers, body: json.encode(map));
final data = xxxFromJson(response.body);
return data;
} catch (e) {
print(e);
return null;
}
}
I solved the problem by using the send() method of the HTTP (More info) package
Future<dynamic> getGoodSolution() async {
final url = Uri.parse('$url');
final headers = {HttpHeaders.contentTypeHeader: 'application/json',HttpHeaders.authorizationHeader: 'Bearer mytoken123'};
var map = <String, dynamic>{};
map["xxx"] = "123";
try {
var request = http.Request('POST', url);
request.headers.addAll(headers);
request.body = json.encode(map);
var streamedResponse = await request.send();
var response = await http.Response.fromStream(streamedResponse);
final data = xxxFromJson(response.body);
return data;
} catch (e) {
print(e);
return null;
}
}
There is an issue ongoing on the Flutter repo which describes your problem.
One of the given workarounds is to use a HttpClient and to set the allowLegacyUnsafeRenegotiation property to true
void main() async {
final context = SecurityContext.defaultContext;
context.allowLegacyUnsafeRenegotiation = true;
final httpClient = HttpClient(context: context);
final client = IOClient(httpClient);
await client.get(Uri.parse('https://your_uri.net'));
}
This solution will only work on mobile though, the http package should not be used in Web mode.

How to upload multiple Images through Api

I am trying to Upload Multiple Images through Api but i am not understanding how to send a list, I can upload a single image though. Tried alot of searches but does'nt helped, i also import multi_image_picker i can pick the images but the problem is in uploading.
Future<Map<String, dynamic>> _uploadImage(File image) async {
String value = '';
SharedPreferences pref2 = await SharedPreferences.getInstance();
value = pref2.getString("user_role");
final mimeTypeData =
lookupMimeType(image.path, headerBytes: [0xFF, 0xD8]).split('/');
// Intilize the multipart request
final imageUploadRequest = http.MultipartRequest('POST', apiUrl);
// Attach the file in the request
final file = await http.MultipartFile.fromPath('photo', image.path,
contentType: MediaType(mimeTypeData[0], mimeTypeData[1]));
// Explicitly pass the extension of the image with request body
// Since image_picker has some bugs due which it mixes up
// image extension with file name like this filenamejpge
// Which creates some problem at the server side to manage
// or verify the file extension
imageUploadRequest.files.add(file);
imageUploadRequest.fields['mobile'] = _mobileNo.text;
imageUploadRequest.headers.addAll({
'Content-Type': 'application/json',
'Authorization': Constants.authToken,
});
var response = await imageUploadRequest.send();
if (response.statusCode == 200) print('Done!');
final respStr = await response.stream.bytesToString();
return json.decode(respStr);
}
this an example of uploading files to your API with HTTP package
import 'package:http/http.dart' as http;
void uploadFiles(List<File> files) async {
final url = YOUR-API-LINK;
for (var file in files) {
// Create a multipart request
var request = http.MultipartRequest('POST', Uri.parse(url));
// Add the file to the request
request.files.add(http.MultipartFile.fromBytes(
'file',
file.readAsBytesSync(),
filename: file.path.split('/').last,
));
// Send the request
var response = await request.send();
// Check the status code
if (response.statusCode != 200) {
print('Failed to upload file');
}else{
print response.body;
}
}
}
for Dio use this
void uploadFiles(List<File> files) async {
final url = YOUR-API-LINK;
// Create a Dio client
var dio = Dio();
// Create a FormData object
var formData = FormData();
// Add the files to the FormData object
for (var file in files) {
formData.files.add(MapEntry(
'file',
await MultipartFile.fromFile(file.path, filename: file.path.split('/').last),
));
}
// Send the request
var response = await dio.post(url, data: formData);
// Check the status code
if (response.statusCode != 200) {
print('Failed to upload files');
}else {
print(response.data)
}
}
as you can see there not much difference between them in http you use MultipartRequest in dio you use FormData.

How can I use the returned value of data I got from my shared preference json file as a parameter

how can i use this as my url parameter
userData['UserName']
I have json data in my shared preference file. So I tried to get the username
of the signed in user because I want to use as a parameter to an endpoint.
I can print the username quite ok on the console but when tried to add it
on the link, the statusCode response I get is:
null.
E/flutter ( 906): Receiver: null
E/flutter ( 906): Tried calling: []("UserName")
please how can I extract his username and add it to the endpoint:
Here's the endpoint that shared preference snippet that gives me the
username:
var q;
var userData;
void _getUserInfo() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
var userJson = localStorage.getString('loginRes');
user = json.decode(userJson);
setState(() {
userData = user;
});
print(userData['UserName']);
}
and this is where I want to use it, on the get request link below:
Future<void> get_farmer_eop() async {
final response = await http.get(
'http://api.ergagro.com:112/GenerateFarmersEop?farmerBvn=${widget.result}&dcOid=${widget.dc_result}&agentName=${userData['UserName']}',
headers: _setHeaders());
print('${response.statusCode}popo');
if (response.statusCode == 200) {
final jsonStatus = jsonDecode(response.body);
setState(() {
q = jsonStatus['Eop'];
});
print('trandid');
print('${q['TransId']}kukuk');
} else {
throw Exception();
}
}
_setHeaders() => {
'Content-type': 'application/json',
'Accept': 'application/json',
};
But on the console I print the username and if I tried to hardcode the agentName which is the username parameter example agentName=johndoh it works but when userData['UserName'] I keep getting null please can anyone help me?
If _getUserInfo not returning anything then why to create a separate method, try below code. It should work.
Future<void> get_farmer_eop() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
var userJson = localStorage.getString('loginRes');
user = json.decode(userJson);
final response = await http.get(
'http://api.ergagro.com:112/GenerateFarmersEop?farmerBvn=${widget.result}&dcOid=${widget.dc_result}&agentName=${user['UserName']}',
headers: _setHeaders());
You are using a wrong formatted url, try this instead:
final response = await http.get(
"http://api.ergagro.com:112/GenerateFarmersEop?farmerBvn=${widget.result}&dcOid=${widget.dc_result}&agentName=${userData['UserName']}",
headers: _setHeaders());

How to get the token for register api in flutter

I am having the Url for Token generation,by using http post i am getting the token.now my problem was i have to use the generated token as header in register api(another api).
Future<Map<String, dynamic>> fetchPost() async {
print('feg');
final response = await http.post(
'/rest_api/gettoken&grant_type=client_credentials',
headers: {HttpHeaders.authorizationHeader: "Basic token"},
);
final responseJson = json.decode(response.body);
print("Result: ${response.body}");
//return Post.fromJson(responseJson);
return responseJson;
}
here i am getting the token i want to use that token to register api
Future<Register> fetchPost() async {
print('feg');
final response = await http.post(
'your base url/rest/register/register',
headers: { HttpHeaders.authorizationHeader: "Bearer token",
HttpHeaders.contentTypeHeader: "application/json"},
);
var responseJson = json.decode(response.body);
print("Result: ${response.body}");
return Register.fromJson(responseJson);
}
this is the post method for register api,i want to use previously generated bearer token in above api headers.
Another option, is use secure storage whit Keychain (Android) and Keystore (iOS)
https://pub.dev/packages/flutter_secure_storage
Add in your pubspec.yaml
dependencies:
flutter_secure_storage: ^3.2.1+1
And in your code, import library and save
Future<Map<String, dynamic>> fetchPost() async {
final storage = FlutterSecureStorage();
print('feg');
final response = await http.post(
'/rest_api/gettoken&grant_type=client_credentials',
headers: {HttpHeaders.authorizationHeader: "Basic token"},
);
final responseJson = json.decode(response.body);
print("Result: ${response.body}");
//return Post.fromJson(responseJson);
/// Write token in token key with security
await prefs.write(key: 'token',value: responseJson['token']);
return responseJson;
}
If you need read, use this code:
Future<Register> fetchPost() async {
final storage = FlutterSecureStorage();
print('feg');
String token = await storage.read(key: 'token');
final response = await http.post(
'your base url/rest/register/register',
headers: { HttpHeaders.authorizationHeader: token,
HttpHeaders.contentTypeHeader: "application/json"},
);
var responseJson = json.decode(response.body);
print("Result: ${response.body}");
return Register.fromJson(responseJson);
}
you can save the generated token in the shared preferences. Then you can use it in any request later.
first add in pubspec.yaml
dependencies:
shared_preferences: ^0.5.3+4
then import it in your code:
import 'package:shared_preferences/shared_preferences.dart';
so when you get your token
Future<Map<String, dynamic>> fetchPost() async {
print('feg');
final response = await http.post(
'/rest_api/gettoken&grant_type=client_credentials',
headers: {HttpHeaders.authorizationHeader: "Basic token"},
);
final responseJson = json.decode(response.body);
print("Result: ${response.body}");
//return Post.fromJson(responseJson);
SharedPreferences prefs = await SharedPreferences.getInstance();
//now set the token inside the shared_preferences
//I assumed that the token is a field in the json response, but check it before!!
await prefs.setString('token',responseJson['token']);
return responseJson;
}
and when you need to send the request just get the token from the shared_preferences:
Future<Register> fetchPost() async {
print('feg');
SharedPreferences prefs = await SharedPreferences.getInstance();
String token = prefs.getString('token');
final response = await http.post(
'your base url/rest/register/register',
headers: { HttpHeaders.authorizationHeader: token,
HttpHeaders.contentTypeHeader: "application/json"},
);
var responseJson = json.decode(response.body);
print("Result: ${response.body}");
return Register.fromJson(responseJson);
}