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

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

Related

Make a post HTTP

I follow the below code, but it seems not to work:
var body = jsonEncode(<String, String>{
'uid': uid,
'limit': '10',
'offset': '2',
'action': 'feed',
});
final response = await http.post(
Uri.parse('http://abc.or/fb/selectPosts.php'),
body: body,
);
if (response.statusCode == 200) {
List<Post> posts = [];
// If the server did return a 200 OK response,
// then parse the JSON.
print((jsonDecode(response.body)));
return List<Post>.from(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to update album.');
}
My API looks like this: http:/abc.or/fb/post.php?uid=aaaa&limit=10&offset=2&action=feed
try this.
import 'package:http/http.dart';
...
static const urlPrefix = 'https://jsonplaceholder.typicode.com';
...
Future<void> makePostRequest() async {
final url = Uri.parse('$urlPrefix/posts');
final headers = {"Content-type": "application/json"};
final json = '{"title": "Hello", "body": "body text", "userId": 1}';
final response = await post(url, headers: headers, body: json);
print('Status code: ${response.statusCode}');
print('Body: ${response.body}');
}
Those are query fields not request body fields.
They are passed in the link or as queryparematers in a Uri
final response = await http.get(
Uri(
path: <your url without the queries(http://abc)>,
query: <Your queries as they are in the string (uid=aaaa&limit=10&offset=2&action=feed), you can use string interpolation to fix the values in or better still use queryparematers, not both>
queryParameters : <String, dynamic>{ 'uid': uid, 'limit': 10, 'offset': 2, 'action': feed },)
);
I use a get method which should be the standard for such url. Do confirm from whoever wrote the api if it is a uses a get or post method.

how to post form data request using flutter in http package

I want to send form data in flutter using the HTTP package. Getting the error:FormatException: Unexpected character (at character 1)
I/flutter (30465):
I am sending the form data in the HTTP post request.
Future<void> authethicate(
String schoolName,
String password,
) async {
try {
final url = 'https://yobimx.com/citykey/api/users/login';
final response = await http.post(url, body: {
'email': 'usamashafiq199#outlook.com',
'password': '123',
}, headers: {
"Content-Type": "application/x-www-form-urlencoded",
});
print(
json.decode(response.body),
);
final responseData = json.decode(response.body);
} catch (error) {
print(error);
}
}
I have to use a multipart request for request. Thanks for your help.
Future<void> authethicate(
String schoolName,
String password,
) async {
try {
final url = Uri.parse('https://yobimx.com/citykey/api/users/login');
Map<String, String> requestBody = <String, String>{
'email': 'usamashafiq199#outlook.com',
'password': '123'
};
var request = http.MultipartRequest('POST', url)
..fields.addAll(requestBody);
var response = await request.send();
final respStr = await response.stream.bytesToString();
print(
jsonDecode(respStr),
);
print("This is the Status Code$respStr");
var encoded = json.decode(respStr);
print(encoded['status']);
print('This is the userId${encoded['data']['user_id']}');
} catch (error) {
print(error);
}
}

Could not set header with dio

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

I would like to upload a image and profile data in Multipart/Formdata format in flutter when hit a api i got response failed

Here is my post api code i try to upload file (image from image picker)and profilePojo(data like username ,fname, lastname etc.) when i run code i got result failed .
'''
void addData(final profilePojo) async {
SharedPreferences preferences = await SharedPreferences.getInstance();
String token = preferences.getString('token');
FormData formData = FormData.fromMap({
"file": await MultipartFile.fromFile("./text.txt",filename: "upload.txt"),
"profilePojo":profilePojo,//profilePojo means i pass heaar string of data on button click
});
String url =pass here url
http
.post(
url,
headers: {
HttpHeaders.authorizationHeader: 'Bearer $token',
// "Content-Type":"multipart/form-data",
"accept": "application/json",
},
body: formData.toString()
)
.then((response) {
if (response.statusCode == 200) {
var myData = json.decode(response.body);
if(myData['result']=="success"){
setState(() {
print(myData);//print response success
_showDialog();
getData();
});}
else{
print(response.statusCode);
print(myData);
}
} else {
print(response.statusCode);
print("object");
}
});
}
'''
I'm currently using dio for this kind of requests, here is my example:
final futureUploadList = imageList.map((img) async {
print(img.path);
return MultipartFile.fromFile(img.path);
});
final uploadList = await Future.wait(futureUploadList);
FormData data = FormData.fromMap({
"images": uploadList
});
dio.post('/images',
data: data, options: Options(headers: {'Authorization': 'Bearer abcd'}));

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