I need to send a large object with my post method. but it kept giving me error.
Future getResults() async {
var res = await http.post('$SERVER_IP/api/anything/search',
headers: {'Authorization': token, "Accept": "application/json"},
body: {
"name": "",
"type": "",
"organization": "",
"state": "CA",
"appliesTo": {
"Camp": "true",
"Fees": "false",
"Lessons": "false",
},
}).catchError((e) => print({"error": e}));
return json.decode(res.body);
}
I realized that body only accept Map<String, String>. So I added json.encode to my "appliesTo" object.
Future getResults() async {
var res = await http.post('$SERVER_IP/api/anything/search',
headers: {'Authorization': token, "Accept": "application/json"},
body: {
"name": "",
"type": "",
"organization": "",
"state": "CA",
"appliesTo": json.encode({
"Camp": "true",
"Fees": "false",
"Lessons": "false",
}),
}).catchError((e) => print({"error": e}));
return json.decode(res.body);
}
After that it worked and I got a returned data. But my server was ignoring whole "appliesTo" object. So I didn't get the expected data. it's not a problem in my server. I tested it with postman. this flutter http post is not sending proper json body.
So my question is how to attatch large object to the body? was using json.encode at the middle of the object wrong? what is the proper way of doing it? can anyone help?
PS: I wraped the whole Map with json.encode and it gave me error
The documentation of the http package states that
If body is a Map, it's encoded as form fields using encoding. The content-type of the request will be set to "application/x-www-form-urlencoded"; this cannot be overridden.
If you want to send JSON data instead, you have to encode the body manually. Since the content type defaults to text/plain if body is a String, you also have to set the Content-Type header explicitly.
http.post('$SERVER_IP/api/anything/search',
headers: {
'Authorization': token,
"Accept": "application/json",
"Content-Type": "application/json"
},
body: json.encode({
"name": "",
"type": "",
"organization": "",
"state": "CA",
"appliesTo": {
"Camp": "true",
"Fees": "false",
"Lessons": "false",
},
}))
Related
How do you correctly add this kind of query parameters to a Dart http get request. This is my code
String? token;
String? baseUrl = 'vps';
String? path = 'web/session';
Map<String, dynamic> query ={
"jsonrpc": "1.0",
"method": "call",
"id": "2",
"params": {
"login": username,
"password": password,
"db": "dev.sf.com",
"context": {}
}
};
Uri uri = Uri.http(baseUrl.toString(), '$path/$endPath');
if (query != null) {
uri = Uri.http(baseUrl.toString(), '$path/$endPath', query);
}
return http.get(uri, headers: {
'Authorization': 'Bearer $token',
'Accept': 'application/json',
});
but i get this error
[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: type '_InternalLinkedHashMap<String, Object>' is not a subtype of type 'Iterable<dynamic>'
Try to send primitive types like int, string, boolean, etc. You send a Map as "params", this shouldnt work.
Map<String, dynamic> query ={
"jsonrpc": "1.0",
"method": "call",
"id": "2",
"login": username,
"password": password,
"db": "dev.sf.com",
};
Alternative (and better imo): Make a post request and send it inside the body.
I have written the api call like this:
var response = await http.post(
Uri.parse("http://api.msg91.com/api/v2/sendsms"),
headers: {
"Content-Type": "application/json",
"authkey": "API key"
},
body: jsonEncode({
"sender": "note",
"route": "4",
"country": "91",
"flash": 1,
"sms":
{"message": "Message1", "to": "9999999999"}
}),
);
But this giving me error : {type: error, message: Invalid content type.Please send data in formdata,application/xml,application/json format, code: }
How can I correct this?
Try removing theses
"Content-Type": "application/json"
or replace it with
"Content-Type": "application/xml"
You should use multipart/form-data as content-type ->
"Content-Type": "multipart/form-data"
I have a JSON request as below:
{
"fieldOne": 12345,
"fieldTwo": 1234,
"fieldThree": "2019-12-05T12:32:42.323905",
"fieldFour": "string",
"fieldFive": 5432,
"fieldSix": "string",
"fieldSeven": "string",
"fieldEight": "string"
}
I need to send the complete request JSON object inside a field in response. My Wiremock stub JSON is,
{
"request": {
"method": "POST",
"urlPath": "/endpoint"
},
"response": {
"status": 200,
"jsonBody": {
"request": "{{{request.body}}}", //If I remove quotes here then I get error so I added the quotes
"anotherField": "string"
},
"headers": {
"Content-Type": "application/json;charset=UTF-8"
},
"transformers": ["response-template"]
}
}
How can I send request body in a field in response?.
I now get error:
Illegal unquoted character ((CTRL-CHAR, code 10)):
has to be escaped using backslash to be included in string value\n at [Source: (
Edit:-
I was using wiremock 2.19.0 version which is causing this issue. I upgraded the version to 2.21.0 and now the issue is resolved
But in the response I still have the below problem where the request body is within double quotes which is an invalid JSON. Response:-
{
"request": "{ //Here the double quotes should not be present before curly brace
"fieldOne": 12345,
"fieldTwo": 1234,
"fieldThree": "2019-12-05T12:32:42.323905",
"fieldFour": "string",
"fieldFive": 5432,
"fieldSix": "string",
"fieldSeven": "string",
"fieldEight": "string"
}",
"anotherField": "string"
}
Use body instead of jsonBody. Then the response message(the content present within double quotes in body) can be formatted in whatever way required.
This will work with wiremock 2.19.0 version as well
{
"request": {
"method": "POST",
"urlPath": "/endpoint"
},
"response": {
"status": 200,
"body": "{\"request\": {{{request.body}}}, \"anotherField\": \"string\" }",
"headers": {
"Content-Type": "application/json;charset=UTF-8"
},
"transformers": ["response-template"]
}
}
I'm trying to query ArcGIS Rest API from Google Apps script. Building the request in Postman works perfectly fine, but when I get the code into apps script, I'm having trouble that I cant seem to figure out. Here's the code:
function callEsri () {
var url = "https://services3.arcgis.com/GVgbJbqm8hXASVYi/arcgis/rest/services/Trailheads/FeatureServer/0/query"
var params =
{
"async": true,
"crossDomain": true,
"url": "https://services3.arcgis.com/GVgbJbqm8hXASVYi/arcgis/rest/services/Trailheads/FeatureServer/0/query",
"method": "POST",
"headers": {
"Content-Type": "application/x-www-form-urlencoded",
"User-Agent": "PostmanRuntime/7.20.1",
"Accept": "*/*",
"Cache-Control": "no-cache",
"Postman-Token": "[TOKEN]",
"Host": "services3.arcgis.com",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "125",
"Connection": "keep-alive",
"cache-control": "no-cache"
},
"data": {
"f": "json",
"where": "CITY_JUR LIKE '%Los Angeles%'",
"outSr": "4326",
"outFields": "TRL_NAME,ELEV_FT,CITY_JUR,PARK_NAME,FID"
}
}
var response = UrlFetchApp.fetch(url, params);
var json = response.getContentText();
var data = JSON.parse(json);
Logger.log(data);
}
The Error I am getting is: Execution failed: Attribute provided with invalid value: Header:Host (line 28, file "Code")
Any reason why Google is not recognizing this and is there a way to fix this? Any help/advice is greatly appreciated.
As #TheMaster has already noted in the comments. You are already specifying the Host in the url.
Also you can take a look at the official documentation of URLFetchApp.
And in case you want more information in the head here you have the mozilla documentation on that header and also the RFC specifying the Host header.
I has http request with body:
endpoint = http://127.0.0.1:54400/json
reqBody:
{
"action": "Handler:GET_DICTIONARY",
"locale": "ro",
"data": {"dictionary_type":"MTS"}
}
I need to get stubbed response.
Here my Wiremock mapping:
{
"request": {
"method": "POST",
"bodyPatterns": [
{
"contains": "Handler:GET_DICTIONARY"
}
]
},
"response": {
"headers": {
"Content-Type": "application/json"
},
"status": 200,
"fixedDelayMilliseconds": 3000,
"bodyFileName": "t2a/micb/webclient/_mts_response.json"
}
}
But I has many another requests that content request's body with text:
"Handler:GET_DICTIONARY"
So as result I need to mapping also by
"dictionary_type":"MTS"
because text
and
"dictionary_type":"MTS" AND "Handler:GET_DICTIONARY" create UNIQUE request.
So how I can mapping by request's body use this two matches?
I would suggest to add "matchesJsonPath" in addition to your "contains"
"bodyPatterns": [
{
"matchesJsonPath": "$.data[?(#.dictionary_type == 'MTS')]"
}
]
That will guarantee that all the request with dictionary_type = MTS will mapped to that response.