I want to pass base64Encode string to my web API. I could encode image and pass base64Encode string to my api but i got "Request-URI Too Long" message from API.
how can i solve this problem ?
static Future<AskModel> addArticle(String title, String content, String base64Image) async {
var url = Uri.http(Config().baseUrl, Config().baseUrlPathAddArticles, {
'title': title,
'content': content,
'base64Image': base64Image,
});
var response = await http.post(url);
if (response.statusCode == 200) {
var jsonString = response.body;
return askModelFromJson(jsonString);
} else {
return null;
}
}
As your using a POST method, so you can set your title,content and base64Image in the body instead of in the url : https://flutter.dev/docs/cookbook/networking/send-data#2-sending-data-to-server
Related
I have code like this:
Future<http.Response> makeRequest() async {
return await http.get(Uri.parse(url));
}
my "url" is a string, and it is working. From the internet i got string like "10" or "125", but when i use this method in my project and im converting it to string it only writes me an error:
Instance of 'Future Response'
, how can i take my string from the internet?
this is my url:
https://apialgorytm20210606150610.azurewebsites.net/algorytm/5w5
Future<String> getObjectFromAPI() async {
var response = await http.get(Uri.parse('www.myAPI.com/getData'),); //1
if (response.statusCode == 200) { //2
return(jsonDecode(response.body)["yourObjectHere"]); //3
} else {
return 'error';
}
}
Here you go.
Put your API url in line 1.
Line 2 checks if you receive a 200OK return or some kind of error code. Line 3 prints the decoded JSON response from the API, and you can enter the specific object you want to fetch as well
Future makeRequest() async {
var res= await http.get(Uri.parse(url));
If(res.statusCode==200){
print(res.body);
return res.body;}else{return null;}
}
now use the above function
var data=makeRequest();
print(data);
I have to send a multipart HTTP post request that contains a image, body and header, Please find the body format
body: {
"Id":Id,
"Details": {
"name": Name,
"centroid": centroid,
"attribute": {
"boundaryOpacity": boundaryOpacity,
"boundaryWeight": boundaryWeight,
"boundaryColor": boundaryColor,
"labelColor": labelColor,
},
},}
headers: {
'tenantId': tenantId,
'Content-Type': 'multipart/form-data',
'x-access-token': token
},
I have to send image along with this request .Please help me with this.
You can convert your map into multipartRequest and set your headers in multipartRequest.
Future<void> addProject(Project project, [File? file]) async {
final url = Uri.parse('$baseUrl/api/projects');
final format = DateFormat('yyyy-MM-dd');
final completionDate = format.format(project.completionDate);
final data = {
'id': project.id,
'title': project.title,
'description': project.description,
'image': project.image,
'completion_date': completionDate,
};
try {
var request = http.MultipartRequest('POST', url);
request = jsonToFormData(request, data);
request.headers['X-Requested-With'] = "XMLHttpRequest";
request.headers['Authorization'] = "Bearer $authToken";
if (file != null) {
request.files
.add(await http.MultipartFile.fromPath("image", file.path));
}
final response = await request.send();
final responseData = await response.stream.toBytes();
final responseString = String.fromCharCodes(responseData);
print(responseString)
notifyListeners();
} catch (error) {
print('Error add project $error');
throw (error);
}
}
jsonToFormData(http.MultipartRequest request, Map<String, dynamic> data) {
for (var key in data.keys) {
request.fields[key] = data[key].toString();
}
return request;
}
You can't send json encoded string with multipart, you have to do it formdata way, you may need to update your backend code
final req = http.MultipartRequest('POST', url);
// Write your add files statement here
req.fields['id'] = id; // This is your id field
req.fields['details[name]'] = Name; // This is name field in details object
req.fields['details[attribute][boundaryOpacity]'] = boundaryOpacity; // This is how you write nested fields
You can follow same pattern for other fields as well, you need to implment a check for null field, assuming id can be null, write it as follows
req.fields['id'] = id != null ? id : ''; // If it is null convert it to empty string or don't include it
Alternate solution
Add a data field and convert entire payload to json string and decode at backend.
What is JSON.stringify() Equal method in Dart or Flutter.
Actually my Backend Services Expecting String Object. How I need to convert From JSON to String Like Below.
HTTP Request Method
Future<String> createUser(SignupUser data) async {
NameReq111 req111 = NameReq111(
firstName: 'dfgdfg',
lastName: 'KKK',
email: 'kvr#gmail.com',
phoneNumber: '9704334584');
ReqNameObject reqName = ReqNameObject(data: req111);
var jsncode = jsonEncode(reqName.toMap());
// It Will Print : {data: {fisrtName:Siva, lastName:Joythi,email:kvr#gmail.com, phoneNnumber:9090909090}}
print(json.decode(jsncode));
//It will Print : {"data": {"fisrtName":"Siva", "lastName":"Joythi","email":"kvr#gmail.com", "phoneNnumber":"9090909090"}}
// But Expected Output Will be:
// '{"data": {"fisrtName":"Siva", "lastName":"Joythi","email":"kvr#gmail.com", "phoneNnumber":"9090909090"}}'
final response = await client.post(
"$baseUrl" + "/urlmethoName",
headers: {"content-type": "application/json", 'charset': 'UTF-8'},
body: json.decode(jsncode),
);
if (response.statusCode == 200) {
return response.body;
} else {
return response.body;
}
}
Output:
My Backend Language Expecting below format:
'{"data": {"fisrtName":"Siva", "lastName":"Joythi","email":"kvr#gmail.com", "phoneNnumber":"9090909090"}}'
How we can do that in Flutter.
Could you please help me. Thanks in advance !!!.
Use jsonEncode(obj) to generate a String in json format
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());
});
}
in postman body:
id:2
images[]:image1 base64
image[]:image2 base64
how to set body to send request?
this my code
var uri = 'url';
var images = List<String>();
Map data = {
'id': id,
'images[]' : images,
};
var body = json.encode(data);
final response = await http.post(uri, body: body);
print("${response.statusCode}");
print("${response.body}");
if (response.statusCode == 200) {
return Model.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to load post');
}
response is failed
what's wrong with my code?