I tried to follow this: https://flutter.dev/docs/cookbook/networking/send-data but code it's not working and i dont know why. Can someone help me and tell me what I have wrong or some video I could use to implement those functions correctly?
What I want to do is to send all the information from a form to the server.
My code: https://github.com/guillemrh/urbix/blob/master/lib/screens/signup_screen_administrador.dart
Thank you
The endpoint http://ec2-52-47-176-18.eu-west-3.compute.amazonaws.com/reg/us/ does not support application/json content type. According to this stackoverflow answer http package only has 3 types: String, List or Map. Try this:
var mapData = new Map<String, dynamic>();
mapData['firstname'] = firstname;
mapData['lastname'] = lastname;
mapData['username'] = username;
mapData['email'] = 'email;
mapData['passw'] = passw;
map['user_type'] = 'Administrador';
final http.Response response = await http.post(
'http://ec2-52-47-176-18.eu-west-3.compute.amazonaws.com/reg/us/',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: mapData
),
);
Also security wise. When dealing with user information such as name, password, and email. Please use HTTPS. You can achieve this on AWS by throwing a load balancer in front of the API server.
Related
I want to pull certain headers and items under the headers as string data from the JSON.
Map dataSignUpEmployeer = {
'corporationName': employeer.getCorporationName(),
'webSiteName': employeer.getWebSiteName(),
'email': employeer.getEmail(),
'password': employeer.getPassword(),
};
String bodySignUpEmployeer = json.encode(dataSignUpEmployeer);
postDataSignUpEmployeer() async {
final response = await http.post(
Uri.parse(urlSignUp),
headers: {"Content-Type": "application/json"},
body: bodySignUpEmployeer,
);
return response.body;
}
response.body return JSON
Eesponse.body's return:
Please help me in any way.
your code is working as well i see so i think you wrong in a part of your code for get the success: true from your response body so maybe you need to authorize your user in header of post method with Token. to get back success true and get all of each user data. any way we should see your api url.
I am using Dart Shelf framework for building an API. Get works fine but I am having issues with post. I couldn't access any of the body parameters of the post request in my server. Here is what I have tried.
// shelf-router
router.post('/login', (Request req) async {
final body = await req.readAsString();
// to check
print(body); // outputs null
return
Response.ok('OK');
});
How am I testing this?
Using postman with the endpoint and body type raw (JSON).
payload as
{
"user":"testUser",
"password":"p455w0rd"
}
I even tried setting contenttype header to application/JSON but no luck there too.
Try this inside your request handler function..
final String query = await request.readAsString();
Map queryParams = Uri(query: query).queryParameters;
print(queryParams);
final String query = await request.readAsString();
// Map<String, String> queryParams = Uri(query: query).queryParameters;
Map queryParams = jsonDecode(query);
print(queryParams['user']);
I can receive the parameter from the postman with form-data.
I am using shelf_route in the server.
If this is similar to you, you can follow this:
https://stackoverflow.com/a/74255231/17798537
I have a flutter app and I'm using back4app.com and Parse RESTful api to register my users, I have read their docs about logging in users but I dont know how to pass my username and password in URL parameters as JSON encoded :
I tried this method:
Future <void>loginMethod(String username,String password) async {
var url = Uri.parse('https://myshoppingapp.b4a.io/login/$username:$password');
final response = await http.get(url, headers: {
'X-Parse-Application-Id': kParseApplicationId,
'X-Parse-REST-API-Key': kParseRestApiKey,
'Content-Type': 'application/json'
},);
final exData = jsonDecode(response.body);
print(exData);
but I've got some errors
Don't use the GET method while sending your personal data to the server.
GET method data is sent data to the server followed by the URL like append with URL request which will be seen to everyone like below.
var url = Uri.parse('https://myshoppingapp.b4a.io/login/$username:$password');
This is how your personal data can be readable from a URL in a GET Method.
'https://myshoppingapp.b4a.io/login/Mehran#metra.org:abcd12345'
For login requests, we should use the POST method. Because our login data is secure which needs security. When using the POST method the data is sent to the server in a bundle.
Future loginMethod(String username,String password) async {
var res = await http.post(Uri.parse('https://myshoppingapp.b4a.io/login/'),
body: {"username": username, "password": password});
print('res : ${res.body}');
if (res.statusCode == 200){ final exData = jsonDecode(res.body);
print(exData);
return res.body;
} else{
final exData = jsonDecode(res.body);
print(exData);
return res.statusCode;
}
}
for HTTP basic authentication
final loginUrl = Uri(scheme: 'https', host: 'example.com', port: 8080, userInfo: 'username:password')
http.get(loginUrl)
but pass username and password via url is not recommended cause it's not safe.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#access_using_credentials_in_the_url
so you should do it by using post formdata.
I'm sending JSON data to my Spring API but I always get a bad request. I have tried some things. At first, chanceReward was of type Map<String, Object>. Later I thought it should be a String but it still had a bad request. I researched and thought I needed consumes = "application/json" in the annotation but result is the same. Not sure anymore what to do. Below is the code for my API:
#RequestMapping(value = "/chance/{id}/saveChanceRewards", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public #ResponseBody Map<String, Object> saveChanceRewards(#PathVariable("id") String id,
#RequestBody String chanceRewards) {
try {
JSONArray jsonArray = new JSONArray(chanceRewards);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject JObject = jsonArray.getJSONObject(i);
System.out.println(JObject.getString("name") + " " + JObject.getString("weight"));
}
} catch(JSONException e) {
_log.error("Error parsing JSON");
}
Map<String, Object> map = new HashMap<String, Object>();
// TODO
return map;
}
Below is the ajax code (inside a .jsp):
let arrayRewards = [];
// get the data from dynamic list of text fields
for (let i = 1; i <= chanceRewardCount; i++) {
arrayRewards.push({
name: $('#chanceRewardName' + i).val(),
weight: $('#chanceRewardWeight' + i).val()
});
}
let data = {'data': arrayRewards};
let jsonData = JSON.stringify(data);
$.ajax({
type: 'post',
dataType: "json",
data: data,
contentType: 'application/json',
url: "${home}/chance/${id}/saveChanceRewards",
method: 'post',
success: function(response) {
console.log('response', response);
},
error: function(err) {
console.log('error', err);
}
});
I'm using Spring Framework 3.2.1.
The 400 Bad Request error is an HTTP status code that means that the request you sent to the website server, often something simple like a request to load a web page, was somehow incorrect or corrupted and the server couldn't understand it.
That mean the server not able to understand the request from your ajax.
First, change #RequestBody String chanceRewards to #RequestBody ChanceRewards chanceRewards
And define ChanceRewards and ChanceReward class.
class ChanceReward {
private String name;
private String weight;
// Getter Setter ...
}
class ChanceRewards {
private List<ChanceReward> data;
// Getter Setter ...
}
If still failed, try open inspect mode and click network tab to check the request send from ajax.
Replace double quotes in your url: "${home}/chance/${id}/saveChanceRewards", by backtick.
There are quite a few things going on here, so let's work on them!
First, I see you've stringified the data into jsonData, but your actual ajax post has data: data instead. Easy fix, just swap in the right variable.
Second thing I notice is that you're wrapping the rewards array in an object (with data = {'data': arrayRewards}) but your Java code expects the array itself (JSONArray) right out of the request body. So this will also throw an exception. You don't have to wrap the array with an object if it's not needed.
Lastly, you mention that you always get a "bad request", but what exactly do you mean? An "HTTP 400" error? Some other HTTP error? It might be useful to give more info on the exact error(s) you see on the javascript side and on the Java server side.
All the other things like worrying about making a ChanceReward / ChanceRewards class, accepts/consumes/produces headers, etc., are superfluous at this point. They are boilerplate niceties and you don't need any of them for this to work correctly.
Trying to create a function in apex that will create Google Drive folders when creating a new record in Salesforce.
I have managed to authenticate and handle GET requests just fine. My issue is regarding the POST requests. The code below should create a folder with the label provided in the "title" parameter. The script executes and instead creates an extension-less file without a label.
public void getDriveFiles(HttpResponse authResponse) {
http h = new Http();
Httprequest req = new HttpRequest();
HttpResponse res = new HttpResponse();
Map<String, Object> responseObject = (Map<String, Object>) JSON.deserializeUntyped(authResponse.getBody());
req.setEndpoint('https://www.googleapis.com/upload/drive/v2/files');
req.setMethod('POST');
req.setHeader('Content-type', 'application/json');
req.setHeader('Authorization', 'Bearer '+responseObject.get('access_token'));
String jsonData = '{"title":"NewFolder", "mimeType":"application/vnd.google-apps.folder"}';
req.setBody(jsonData);
res = h.send(req);
system.debug('Response ='+ res.getBody() +' '+ res.getStatusCode());
}
I have a feeling it's my request body but I have no idea what to do to fix it.
You've used the wrong endpoint. Instead of the file endpoint, you're posting to the content endpoint.
So
req.setEndpoint('https://www.googleapis.com/upload/drive/v2/files');
should be (for the v2 API)
req.setEndpoint('https://www.googleapis.com/drive/v2/files');
or (for the v3 API)
req.setEndpoint('https://www.googleapis.com/drive/v3/files');
If you use v3 (which you probably should), your json should change thus
String jsonData = '{"name":"NewFolder", "mimeType":"application/vnd.google-apps.folder"}';