I am new to flutter and I am using mongodb to save the credentials from signup page. When tried to give credentials that already exists server shows a response - 'user already exits' this response was viewed in postman. I am able to get statusCode but I am unable to get the same response in flutter. below is my flutter code.
Future<String> uploadImage(filename) async {
var request = http.MultipartRequest('POST', Uri.parse(serverReceiverPath));
request.files.add(await http.MultipartFile.fromPath('file', filename));
var res = await request.send();
print(res.statusCode);
return null;
}
To get the body response, use res.stream.bytesToString()
Complete code:
Future<String> uploadImage(filename) async {
var request = http.MultipartRequest('POST', Uri.parse(serverReceiverPath));
request.files.add(await http.MultipartFile.fromPath('file', filename));
var res = await request.send();
print(res.statusCode); // status code
var bodyResponse = await res.stream.bytesToString(); // response body
print(bodyResponse);
return null;
}
Related
I'm trying to upload images and some data via API from my app and I have no error in my console and I don't know what's wrong with my function.
This is the code which I use:
upload(File imageFile) async {
var user =
Provider.of<LoginUserProvider>(context, listen: false).userData.data;
DateFormat formater = DateFormat('yyyy-MM-dd');
String formatted = formater.format(dateTime);
var stream =
// ignore: deprecated_member_use
new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
var length = await imageFile.length();
var headers =
Provider.of<LoginUserProvider>(context, listen: false).httpHeader;
var uri = Uri.parse(
"xyz");
var request = new http.MultipartRequest("POST", uri);
request.headers.addAll(headers);
//request.headers.addAll(Environment.requestHeaderMedia);
var multipartFile = new http.MultipartFile(
'attachment',
stream,
length,
filename: imageFile.path,
contentType: MediaType('application', 'x-tar'),
);
request.fields['section_id'] = VillaID.toString();
request.fields['date'] = formatted;
request.fields['description'] = descriptionController.text;
request.files.add(multipartFile);
var response = await request.send();
print(response.statusCode);
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
try {
final streamedResponse = await request.send();
final response = await http.Response.fromStream(streamedResponse);
print(json.decode(response.body));
final responseData = json.decode(response.body) as Map<String, dynamic>;
if (response.statusCode == 200 || response.statusCode == 201) {
return true;
}catch (error) {
print(error);
return false;
}
return true;
}
So can anyone help me with my issue, please!
you are sending the same request twice
1st
var response = await request.send();
Second
final streamedResponse = await request.send();
before sending the same request, create them again.
regarding your code you don't need to create a response again. use the first one in the other places.
Im a newbie to flutter so please if you think the question context is wrong update it, im fetching a data from an SQl server to my flutter app, and i also want to send the users info back to the server after they fill out a form, im using the http.post and i get the response’s body correctly but when i open the Server Url (api url) i dont see it updated with the new info i posted to it, can someone please tell me how Post is supposed to work?
I'm new to Flutter too, this is a working example of how i understand it
class HttpService {
createUser(String name, String lastname) async {
Map data = {'name': name, 'lastname': lastname};
var body = json.encode(data);
var jsonResponse = null;
var response = await http.post(serverUrl + "/create/",
headers: {
HttpHeaders.authorizationHeader: '**Token_here_if_you_use_it**',
HttpHeaders.contentTypeHeader: "application/json",
}, body: body);
jsonResponse = json.decode(response.body);
if (response.statusCode == 201) {
jsonResponse = json.decode(response.body);
if (jsonResponse != null) {
print(jsonResponse.toString());
}
} else {
print(jsonResponse.toString());
}
}
}
In your main.dart :
final HttpService httpService = HttpService();
httpService.createUser(name,lastname);
I use Flutter to make a HTTP-Post to a website to login. If I only send the data to login, the response of the HTTP-Post shows, that I`m not logged in. I tried to find out the cookie the Website sends. I did it with the software Postman. If I add the same cookie, I got at Postman, the HTTP-Post with Flutter works and the response shows, that Im logged in. After a while, the value of the cookie switched and the HTTP-Post via Flutter doent work.
How can I get the information about the actual value of the cookie from the website?
The code looks like this:
Future initiate() async {
ByteData bytes = await rootBundle.load('assets/Certificates/test.crt');
SecurityContext clientContext = new SecurityContext()
..setTrustedCertificatesBytes(bytes.buffer.asUint8List());
var client = new HttpClient(context: clientContext);
IOClient ioClient = new IOClient(client);
var form = <String, String>{
'user':'testuser',
'pass':'testpass',
'logintype':'login',
'pid':'128',
'submit':'Anmelden',
'tx_felogin_pi1[noredirect]':'0'
};
print(form);
var ris = await ioClient.get("https://www.test.de/login");
print(ris.headers);
http.Response res = await ioClient.post("https://www.test.de/login",body:form, headers: {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded", "Cookie": "fe_typo_user=12345"}, encoding: Encoding.getByName("utf-8"));
ioClient.close();
client.close();
print(res.body.length);
return res.body.contains("logout");
}
This is how I get cookie:
static Future<String> login(String username, String password) async {
var url = _session._getUrl('/auth/login');
var map = new Map<String, dynamic>();
map['username'] = username;
map['password'] = password;
final response = await http.post(url, body: map);
var jsonResponse = convert.jsonDecode(response.body);
var cookies = response.headers['set-cookie'];
if (cookies != null) {
var csrf = _session._getCSRF(cookies);
LocalStorage.instance.setString('CSRF', csrf);
print(csrf);
}
return jsonResponse['msg'];
}
I need your help guys. I'm developing a front-end with Blazor which sends request to ASP.Net Core.
I have the following code which gets an API response, in this case it returns the entire body of the response. What I'm trying to get here is the status code of the response only, example (200).
await Http.SendJsonAsync(HttpMethod.Post, "https://da3.mock.pstmn.io/api/register", CurrentUser);
var response = await Http.GetStringAsync("/api/register");
Console.WriteLine(response);
Use the other GetAsync method.
//var response = await Http.GetStringAsync("/api/register");
//Console.WriteLine(response);
var response = await Http.GetAsync("/api/register");
Console.WriteLine(response.StatusCode); // also see response.IsSuccessStatusCode
For POST method you could use SendAsync, you need to use PMC to install Newtonsoft.Json package firstly:
var requestMessage = new HttpRequestMessage()
{
Method = new HttpMethod("POST"),
RequestUri = new Uri("https://localhost:5001/api/default"),
Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(CurrentUser))
};
requestMessage.Content.Headers.ContentType =
new System.Net.Http.Headers.MediaTypeHeaderValue(
"application/json");
var result = await Http.SendAsync(requestMessage);
var responseStatusCode = result.StatusCode;
For GET method,what Henk Holterman has suggested (use Http.GetAsync) works well.
Refer to
https://learn.microsoft.com/en-us/aspnet/core/blazor/call-web-api?view=aspnetcore-3.0#httpclient-and-httprequestmessage-with-fetch-api-request-options
I have REST API that returns if user exists or not by email.
If user exists and I am getting back status OK from API all works fine, but when API response with 404 my app crash. I can't figure out how to check if status is ok or not before app crash and redirect user to register page in case user is not found by API.
Here is code that makes request to api:
string getuserUrl = $"https://localhost:99282/api/users/{email}";
var client = new HttpClient();
var uri = new Uri(getuserUrl);
var result = await client.GetStringAsync(uri);
var userResult = JsonConvert.DeserializeObject<User>(result);
return userResult;
You can use below code to identify whether the API call is success or not.
String URL = "https://localhost:99282/api/users/{email}";
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(URL);
try
{
HttpResponseMessage response = await client.GetAsync(URL);
if (response.IsSuccessStatusCode)
{
// Code 200 - If the API call is sucess
// You redirect to another page
}
else
{
// Show alert for failed calls
}
}
catch (Exception ex)
{
return null;
}
}