Could not set header with dio - flutter

I ma not able to set header with dio.I am tryng to set my access token to the header.I ma trying to set header so that every request doesnt required to call it.Here is my network class where i am trying to call header with dio
My network Class:
class NetworkUtil {
Dio _dio;
String token;
getToken() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
String getToken = preferences.getString(AppPrefernces.LOGIN_PREF);
return getToken;
}
NetworkUtil() {
///Create Dio Object using baseOptions set receiveTimeout,connectTimeout
BaseOptions options = BaseOptions(receiveTimeout: 5000, connectTimeout: 5000);
options.baseUrl = ApiConstants.BASE_URL;
_dio = Dio(options);
_dio.interceptors.add(InterceptorsWrapper(
onRequest: (Options option) async{
//my function to recovery token
await getToken().then((result) {
LoginResponse loginResponse = LoginResponse.fromJson(jsonDecode(result));
token = loginResponse.accessToken;
});
option.headers = {
"Authorization": "Bearer $token"
};
}
));
}
///used for calling Get Request
Future<Response> get(String url, Map<String, String> params) async {
Response response = await _dio.get(url,
queryParameters: params,
options: Options(responseType: ResponseType.json));
return response;
}
///used for calling post Request
Future<Response> post(String url, Map<String, String> params) async {
Response response = await _dio.post(url,
data: params, options: Options(responseType: ResponseType.json));
return response;
}
}

I use this setup and it works fine for me.
Future<Dio> createDioWithHeader() async {
if (_dioWithHeader != null) return _dioWithHeader;
String token = await appSharedPreferences.getToken();
String userAgent = await getUserAgent();
print('User-Agent: $userAgent');
// base config
_dioWithHeader = Dio(BaseOptions(
connectTimeout: 10000,
receiveTimeout: 10000,
baseUrl: Config.apiBaseUrl,
contentType: 'application/json',
headers: {
'Authorization': token,
'User-Agent': userAgent
}));
// setup interceptors
return addInterceptors(_dioWithHeader);
}```

Related

How to fire interceptor with post request and set configurable dio interceptor work every api app

I want to know dio post request how perform interceptor 'onrequest' in response 'onerror'
Above code in 'onerror' request refresh token not working interceptor also any other way
Future getlist() async{
final dio = Dio();
Final storage=Fluttersecurestorage();
String accesstoken =await storage.read('accesstoken');
final response= await dio.post(
url,
data: loginData,
options: Options(headers: {"authorization": 'Bearer $accesstoken'}),
dio.interceptors.clear();
dio.interceptors.add(
InterceptorsWrapper(
onRequest: (request, handler) {
},
onError: (err, handler) async {
if (err.response?.statusCode == 401) {
//request refresh token}
}
}
));

post method with bearer auth in dio in flutter

I tried to make post method with Bearer Auth in dio but I got Http status error [500]
this is my code
sendData() async {
pr.show();
if (_value == null) {
Future.delayed(Duration(seconds: 0)).then((value) {
setState(() {
pr.hide();
utils.showAlertDialog(
select_area, "warning", AlertType.warning, _scaffoldKey, true);
});
});
return;
}
// Get info for attendance
var dataKey = getKey;
var dataQuery = getQuery;
var userToken = getToken;
// Add data to map
Map<String, dynamic> body = {
'key': dataKey,
'worker_id': getId,
'q': dataQuery,
'lat': _currentPosition.latitude,
'longt': _currentPosition.longitude,
'area_id': _value,
};
// Sending the data to server
final uri = utils.getRealUrl(getUrl, getPath);
Dio dio = Dio();
Map<String, String> mainheader = {
"Content-type": "application/json",
"Authorization": userToken,
};
FormData formData = FormData.fromMap(body);
final response = await dio.post(uri,
data: formData, options: Options(headers: mainheader));
var data = response.data;
and also see this image , I can see the token in my function , so what can I do to fix it
I tried this code but also same
dio.options.headers['content-Type'] = 'application/json';
dio.options.headers["authorization"] = "Bearer userToken";
Update -----
this is the details of the 500 error
as you see its same error when I make the post without auth in postman so I think the problem its from headers
and here with auth
The 500 error is a server-side error.
You should be able to find the cause of the problem on the server.

401 on POST requests, how to set up properly http service?

I am trying to fetch data after successful login. I have cookie based auth on backend. I checked the login response and I see that the cookie is present in the headers. I am not sure why my requests are not going with cookie.
I keep getting this in my console, code for not authorized. I/flutter (21293): 401
class Session {
Map<String, String> headers = {};
Future<Map> get(String endpoint) async {
http.Response response = await http.get(Uri.parse("$baseUrl$endpoint"), headers: headers);
print(response.statusCode);
updateCookie(response);
return jsonDecode(response.body);
}
Future<http.Response> post(dynamic data, String endpoint) async {
http.Response response = await http.post(Uri.parse("$baseUrl$endpoint"), body: json.decode(data), headers: headers);
updateCookie(response);
return response;
}
void updateCookie(http.Response response) {
String? rawCookie = response.headers['set-cookie'];
if (rawCookie != null) {
int index = rawCookie.indexOf(';');
headers['cookie'] =
(index == -1) ? rawCookie : rawCookie.substring(0, index);
}
}
}
Tried to print rawCookie as well
I/flutter (21293): _api_key=SFMyNTY.g3QAAAABbQAAAAhpZGVudGl0eXQAAAAHZAAKX19zdHJ1Y3RfX2QAF0VsaXhpci5HYXRld2F5LklkZW50aXR5ZAAGYWN0aXZlZAAEdHJ1ZWQACWF2YXRhcl9pZG0AAAAkNTY4NWMwNTMtYThhMS00MDA5LWJhN2UtZmJkNTkyMjBhM2U1ZAAHY291bnRyeXQAAAAGZAAEZmxhZ20AAAAI8J-HtfCfh7FkAAppc29fbmFtZV8ybQAAAAJwbGQACmlzb19uYW1lXzNtAAAAA3BvbGQABG5hbWVtAAAABlBvbGFuZGQACG51bV9jb2RlbQAAAAM2MTZkAAVwb2ludHQAAAAEZAAKX19zdHJ1Y3RfX2QAEEVsaXhpci5HZW8uUG9pbnRkAAtjb29yZGluYXRlc2gCYRRhNGQACnByb3BlcnRpZXN0AAAAAGQABHNyaWRiAAAQ5mQAC2Rlc2NyaXB0aW9ubQAAAAF4ZAACaWRtAAAAJGM2ZTljY2Q0LTM4MmItNDEzZi04ODYyLTc2ZjM5ZTYxOGFiNGQABG5pY2ttAAAACHRlc3Rzc3Nz.80iQK3sUwPPVj1pkaZsKgMxQ4Lt8aW8-ndYbPSucGag; path=/; HttpOnly
I/flutter (21293): 200
Then I use it
class Items{
Future<Map> fetchItems() async {
final response = await Session().get("/user/items");
return response;
}
}
I had the same problem. I resolved it by using dio and cookiejar instead of HTTP.
Add these dependencies in your pubspec.yaml:
dependencies:
dio: ^4.0.4
dio_cookie_manager: ^2.0.0
cookie_jar: ^3.0.1
Here's an example to use dio:
var dio = Dio(BaseOptions(
connectTimeout: 10000, // in ms
receiveTimeout: 10000,
sendTimeout: 10000,
responseType: ResponseType.plain,
followRedirects: false,
validateStatus: (status) { return true; }
)); // some dio configurations
dio.interceptors.add(CookieManager(CookieJar()));
Response response = await dio.post(
"http://example.com/login",
data: FormData.fromMap(
{
'username': 'myUser',
'password': 'myPassword',
}
)); // cookies are automatically saved
Response nextResponse = await dio.post("http://example.com/user/items");

Flutter - How to send a POST request using HTTP in Dart?

I am using an API that converts HTTP to JSON and to get a response from the server I need to send a post request of HTML however i'm not sure how to do that?
This is my current implementation -
Future<String> test() async {
var link =
await http.get('https://example.com');
var body = parse(link.body);
return body.outerHtml;
}
Future<Album> createAlbum(String html) async {
final http.Response response = await http.post(
'https://www.html2json.com/api/v1',
headers: <String, String>{
'Content-Type': 'text/html; charset=UTF-8',
},
body: html,
);
if (response.statusCode == 200) {
return Album.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to create album.');
}
}
I call this is when my app starts like so,
#ovveride
void initState() {
test().then((body) => createAlbum(body)); //Output returns HTTP error 301, am I doing something wrong?
super.initState();
}
Checked the following code which worked for me.
Future<Album> createAlbum(String html) async {
final http.Response response = await http.post(
'https://www.html2json.com/api/v1',
headers: <String, String>{
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
},
body: html,
);
You need to change the Content-type to application/x-www-form-urlencoded; charset=UTF-8. This should do the trick.
Thanks to DARSH SHAH, I solved this using dio (https://pub.dev/packages/dio).
dynamic response;
Dio dio = Dio();
Future<dynamic> test() async {
dynamic link = await dio.get(
'https://example.com');
return link;
}
Future<dynamic> post(dynamic body) async {
String _baseUrl = "https://html2json.com/api/v1";
var options = Options(
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
followRedirects: false,
);
final response = await dio.post(
_baseUrl,
data: body,
options: options,
);
return response;
}
FloatingActionButton(
onPressed: () async {
dynamic responseHTML = await test();
response = await post(responseHTML.data); //This will contain the JSON response
},
);

How to set headers for POST with flutter and Dio

this is my code below, i'm stuck please help.
void getProducts() async {
String htoken = Utils.prefs.getString("token");
print(htoken);
try {
var dio = Dio(BaseOptions(headers: {"appusertoken": "$htoken"}));
//dio.options.headers["appusertoken"] = "$htoken";
Response response = await dio.post(
'APIURL',
);
print("data coming");
print(response.data);
} on DioError catch (e) {
print(e.response.data);
print(e.response.headers);
print(e.response.request);
}
}
it was throwing an error of data null.
I was able to fix the issues.
Add optional parameter options for dio.post method and define headers with Options class:
void getProducts() async {
String htoken = Utils.prefs.getString("token");
try {
Dio dio = Dio();
Response response = await dio.post("http://URL",
data: {},
options: Options(
headers: {"appusertoken": "$htoken"},
));
print("data coming");
print(response);
} on DioError catch (e) {
print(e.response.data);
print(e.response.headers);
print(e.response.request);
}
}
For example :
Dio _dio = new Dio();
_dio.options.contentType = Headers.formUrlEncodedContentType;
_dio.options.headers['Authorization'] = 'bearer $authToken';
or use :
final Map<String, dynamic> header = {'Authorization': 'bearer $authToken'};
enter code here
final responseData = await _dio.get(
Apis.account_profit,
options: RequestOptions(
method: 'GET', headers: header, baseUrl: Apis.apiBaseUrl),
);