So I was having issues with flutter http package when it came to making a post request so I used dart HttpClient. I made a post request according to what was described somewhere but I am having issues getting response. Here is my code
Future<HttpClientResponse> submit() async {
print('start');
Map<String, dynamic> data = { 'title' : 'My first post' };
String jsonString = json.encode(data); // encode map to json
String paramName = 'param'; // give the post param a name
String formBody = paramName + '=' + Uri.encodeQueryComponent(jsonString);
List<int> bodyBytes = utf8.encode(formBody); // utf8 encode
HttpClientRequest request =
await HttpClient().postUrl(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
// it's polite to send the body length to the server
request.headers.set('Content-Length', bodyBytes.length.toString());
request.headers.set('Content-Type', 'application/json');
request.add(bodyBytes);
print('done');
return await (request.close());
}
How do I get the response from this request?
HttpClientResponse response = await request.close();
response.transform(utf8.decoder).listen((contents) {
print(data); // <- response content is here
});
This will return HttpCLientResponse, more info https://api.dartlang.org/stable/2.6.1/dart-io/HttpClient-class.html
I have found this from the docs
new HttpClient().get('localhost', 80, '/file.txt')
.then((HttpClientRequest request) => request.close())
.then((HttpClientResponse response) {
response.transform(utf8.decoder).listen((contents) {
// handle data
});
});
Or Use http library
I have create a common method which can handle all get Request,
Future<String> getRequest([var endpoints, var queryParameters]) async {
var uri = Uri.https(NetworkUrl.BASE_URL_1, endpoints, queryParameters);
uri.replace(queryParameters: queryParameters);
var response =
await http.get(Uri.encodeFull(uri.toString()));
//Retrun reponse here
if (response.statusCode == 200) return response.body;
}
To get a response from the above method,
Future<String> deletePostApi() async {
await NetworkRepository()
.getRequest(NetworkUrl.deletePost + '${widget.mFeedData.post_id}')
.then((value) {// <=value is json respone
var dataConvertedToJSON = json.decode(value);
print("checkEmailResp" + dataConvertedToJSON.toString());
});
}
Related
When I debug this function I get the http error code 502:
Future<bool> checkSessionID(String sessionId) async {
Uri uri = Uri.parse("https://myurl.com");
var myobj = {
"session": sessionId,
};
HttpClient client = HttpClient(context: SecurityContext()..setTrustedCertificatesBytes(creds.key.codeUnits));
var request = await client.postUrl(uri);
request.headers.set('content-type', 'application/json');
request.add(utf8.encode(jsonEncode(myobj)));
var response = await request.close();
// encode response to json
var json = jsonDecode(await response.transform(utf8.decoder).join());
return json["status"];
}
but when I remove the JSON payload it returns code 200:
Future<bool> checkSessionID(String sessionId) async {
Uri uri = Uri.parse("https://myurl.com");
var myobj = {
"session": sessionId,
};
HttpClient client = HttpClient(context: SecurityContext()..setTrustedCertificatesBytes(creds.key.codeUnits));
var request = await client.postUrl(uri);
//request.headers.set('content-type', 'application/json');
//request.add(utf8.encode(jsonEncode(myobj)));
var response = await request.close();
// encode response to json
var json = jsonDecode(await response.transform(utf8.decoder).join());
return json["status"];
}
when I run this python code it works just fine:
url = 'https://myurl.com'
payload = {"session": session_id}
request = requests.post(url, json = payload, verify="cert.cer")
Am I encoding the json wrong in the dart code or what is my mistake?
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,
))
I have to send api request to upload a file to the server.
the pattern:
repo,
provider
service
i have followed fails because of the response multipartRequest sends
how can i convert the request got into normal get/post request ?
Future mutliPartPostRequest(
{required String method,
required String url,
Map<String, String>? headers,
File? file,
String? document,
Map? data}) async {
Map<String, dynamic> jsonResponse;
try {
var request = http.MultipartRequest(method, Uri.parse(url));
data!.forEach((key, value) {
request.fields[key] = value.toString();
});
request.headers['Authorization'] = headers!['authorization']!;
/// [FILTERING] : the null image if there are no photos in the request it will skip adding the photo in the request
if (file != null) {
var picture = await http.MultipartFile.fromPath("photo", file.path);
request.files.add(picture); //adds the photo to the request
}
// Checking the document if it is empty, if it is empty it will skip to add the document in the request
if (document != null) {
var doc = await http.MultipartFile.fromPath('document', document);
request.files.add(doc); // adds the document to the request
}
///Our case starts from this line, while sending multipart request, the response we get is quite different than the normal json data response.
// response => stores the response got
var response = await request.send().timeout(const Duration(seconds: 10)); //sends the request body to the server
// result => coverts the multipart response got from the server to the normal request
var result = await http.Response.fromStream(response);
jsonResponse = returnResponse(result); /// returns the response according to the status code from [returnResponse] function
} on SocketException {
throw FetchDataException({"detail": "No Internet Connection"});
}
return jsonResponse;
}
I have an app which is using http request for php server.
But I have a problem here.
Future<List<Photo>> fetchPhotos(http.Client client) async {
final response =
await client.get(Uri.parse('https://meshcurrent.online/get_1userdrive.php'));
// Use the compute function to run parsePhotos in a separate isolate.
return compute(parsePhotos, response.body);
}
// A function that converts a response body into a List<Photo>.
List<Photo> parsePhotos(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
}
I have a code like this. I am getting datas from the server. But I want to send a value to php server. and get datas depend on the value.
For instance, I will send username to the php server and I will get the datas about the username parameter. My php codes works but the problem is in flutter code.
Thanks for your helps
If youre tryting to send parameters over a get, you could use something like:
Future<List<Photo>> fetchPhotos(http.Client client) async {
final response = await client
.get(Uri.parse('https://meshcurrent.online/get_1userdrive.php?userId=5'));
if (urlCallResponse.statusCode == 200) {
// Use the compute function to run parsePhotos in a separate isolate.
return compute(parsePhotos, response.body);
} else {
...
}
}
// A function that converts a response body into a List<Photo>.
List<Photo> parsePhotos(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
}
Here is an example on how to do a post:
final response = await post(
Uri.parse(
'http://.../PostCall'),
headers: {
'authorization': getBasicAuth(username, password),
'Content-type': 'application/json',
'Accept': 'application/json',
},
body: json.encode(jobFormValue),
);
if (response.statusCode == 200) {
}
getBasicAuth function:
String getBasicAuth(String username, String password) {
return 'Basic ${base64Encode(utf8.encode('$username:$password'))}';
}
I am not sure what is going on with my function. I am trying to have a generic request function that I can use with any request method (GET, POST, etc...). Everything is working well, except for the POST response, it is missing data. I double checked what is expected to be returned and compared it with the response from Postman and my code. My code produces less data than expected and Postman.
Here is what I am doing
class HttpClientHandler {
String baseUrl = 'jsonplaceholder.typicode.com';
String path = '/posts';
static const Map<String, String> defaultHeaders = {'': ''};
static const Map<String, String> defaultBody = {'': ''};
Future<dynamic> request(HttpMethod method,
{Map<String, String> headers = defaultHeaders,
Map<String, dynamic> body}) async {
var uri = Uri.https(baseUrl, '$path');
var request = http.Request(method.type, uri);
request.headers.addAll(headers);
request.body = body.toString();
var response = await request.send();
if (response.statusCode >= 200 && response.statusCode <= 299) {
String rawData = await response.stream.transform(utf8.decoder).join();
return jsonDecode(rawData);
} else {
throw Exception();
}
}
}
The caller simply does the following:
var _client = HttpClientHandler();
var data = await _client.request(HttpMethod.POST, body: {'title': 'foo', 'body': 'bar', 'userId': 1});
print(data);
The response I get is:
{id: 101}
The expected response is:
{
"title": "foo",
"body": "bar",
"userId": "1",
"id": 101
}
I am using import 'package:http/http.dart' as http; package. Is this a stream, transform, or headers issue?
I found what was wrong in my implementation, I didn't jsonEncode my request body. The test API I am using here replies the same request body it receives. Since I wasn't encoding the body correctly, it only was recognizing the first data being sent.
So, the fix is to change this line:
request.body = body.toString();
to this line:
request.body = jsonEncode(body);
Also, I ended up parsing the stream byte to string differently, from:
String rawData = await response.stream.transform(utf8.decoder).join();
To:
String rawData = await response.stream.bytesToString();