How to create get request with 3 parameters? - flutter

I try to do this like this. But this give me the error : Unhandled Exception: HandshakeException: Handshake error in client (OS Error:
E/flutter (31038): WRONG_VERSION_NUMBER(tls_record.cc:242)) Host name have good name. It's a server.
This is my code. How to do this?
var queryParameters = {
'abc': 'abc',
'bcd': 'bcd,
'cde' : 'cde'
};
var uri = Uri.https('www.xyz.pl:1234', '/admin/api/get', queryParameters);
var response1 = await http.get(uri);

Pseudo
var res = await http.get(
Uri.encodeFull('www.xyz.pl'),
headers : queryParameters);
hardcoded
var res = await http.get(
Uri.encodeFull('www.xyz.pl'),
headers : {
"abc": "abc",
"bcd": "bcd",
"cde": "cde"
});
final statusCode = res.statusCode;
Explanation how to make authenticated requests here - https://flutter.dev/docs/cookbook/networking/authenticated-requests

var queryParameters = {
'abc': 'abc',
'bcd': 'bcd,
'cde' : 'cde'
};
var uri ='www.xyz.pl:1234/admin/api/get'; // your url
bool trustSelfSigned = true;
HttpClient httpClient = new HttpClient()
..badCertificateCallback =
((X509Certificate cert, String host, int port) => trustSelfSigned);
IOClient ioClient = new IOClient(httpClient);
await ioClient.get(Uri.parse(uri), body: queryParameters).then((response) {
if (response.statusCode == 200) {
print(response);
}
Try this code

You can create Map<String, String> headers, body, encoding for pass multiple reguest param. You can check it here.

Related

Flutter http request returns error code 502, but same request in python returns http code 200

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?

how to parse the answer (array) you get in the API (GET) query in flutter

I'm querying get into flutter, and I'm getting back array (one object in the array). I want to parse this answer and assign the data from the array object to the variable. But I can't do it. Here is my request:
Future<Null> example(
String? task_id
) async {
HttpClient client = new HttpClient();
client.badCertificateCallback =
((X509Certificate cert, String host, int port) => true);
final String url = urlVar "?id="+ '$task_id';
final request = await client
.getUrl(Uri.parse(url))
.timeout(Duration(seconds: 5));
HttpClientResponse response = await request.close();
var responseBody = await response.transform(utf8.decoder).join();
Map jsonResponse = json.decode(responseBody);
print(jsonResponse);
}
My answer json
[
{
"id": "d290111e-6c54-4b01-90e6-d701748f0851",
"name": "Parse example",
}
]
I want to parse this answer and assign it to my variables. I did it like when the answer was in the object, I did it like this. But with array not, I will be grateful for help)
var responseBody = await response.transform(utf8.decoder).join();
Map jsonResponse = json.decode(responseBody);
print(jsonResponse);
if (response.statusCode == 200) {
global.taskId = jsonResponse['id'] ;
global.taskName = jsonResponse['name'];
}
Try this
if (response.statusCode == 200) {
global.taskId = jsonResponse[0]['id'] ;
global.taskName = jsonResponse[0]['name'];
}

body not sending using map in flutter

HttpClient client = new HttpClient();
client.badCertificateCallback = ((X509Certificate cert, String host, int port) => true);
String url ='https://dev.jobma.com:8090/v4/jobseeker/login';
Map map = {
"email":"hope#yopmail.com",
"password":"123456"
};
print(map);
HttpClientRequest request = await client.postUrl(Uri.parse(url));
request.headers.set('content-type', 'application/json');
request.add(utf8.encode(json.encode(map)));
HttpClientResponse response = await request.close();
String reply = await response.transform(utf8.decoder).join();
print(reply);
and response from server showing this
{"error": 1, "data": {}, "message": "Please add mandatory fields: email, password"}
It is much easier if you can use http package available in dart pub.
import 'package:http/http.dart' as http;
String url = 'https://dev.jobma.com:8090/v4/jobseeker/login';
Map map = {
"email": "hope#yopmail.com",
"password": "123456"
};
var response = await http.post(url, body: map);
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
It seems that without the "content-length" headers, that server isn't accepting the request properly. This will make your code work:
HttpClient client = new HttpClient();
client.badCertificateCallback =
((X509Certificate cert, String host, int port) => true);
String url = 'https://dev.jobma.com:8090/v4/jobseeker/login';
Map map = {
"email": "hope#yopmail.com",
"password": "123456"
};
print(map);
// Creating body here
List<int> body = utf8.encode(json.encode(map));
HttpClientRequest request = await client.postUrl(Uri.parse(url));
request.headers.set('content-type', 'application/json');
// Setting the content-length header here
request.headers.set('Content-Length', body.length.toString());
// Adding the body to the request
request.add(body);
HttpClientResponse response = await request.close();
String reply = await response.transform(utf8.decoder).join();
print(reply);

How To deal with Response after post request dart httpClient

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

How do I upload image in Flutter App to my server and decode the json response from the server?

I have an Endpoint on my server which accepts multipart/form-data and sends back json as a response.
I want to send an Image from my flutter App to my server and Decode the json received from the server.
You can use http.MultipartRequest for that
Example:-
static Future<UploadImageRes> uploadImage(int id, File imageFile) async {
if (imageFile != null) {
var stream = new http.ByteStream(imageFile.openRead());
var length = await imageFile.length();
String token = PreferenceUtils.getString(AppConstants.LOGGED_IN);
var uri = Uri.parse(UrlConstants.ADD_RECIPE_PHOTO);
LogUtils.d("====uri : $uri");
LogUtils.d("====recipeId : $id");
var request = new http.MultipartRequest("POST", uri);
String fileName = imageFile.path.split("/").last;
var multipartFile = new http.MultipartFile('photo', stream, length,
filename: fileName, contentType: new MediaType('image', 'jpeg'));
request.headers.addAll({"Authorization": "Bearer $token"});
request.files.add(multipartFile);
request.fields["recipeId"] = "$id";
var response = await request.send();
var statusCode = response.statusCode;
LogUtils.d("====statusCode : $statusCode");
if (statusCode < 200 || statusCode >= 400) {
throw new ApiException("Uploading failed");
}
final respStr = await response.stream.bytesToString();
return Future.value(UploadImageRes.fromJson(JsonDecoder().convert(respStr)));
} else {
throw new ApiException("Uploading failed");
}
}
In final respStr = await response.stream.bytesToString(); you will get your api response