I am posting a as shown below:
function myFunction() {
var headers = {
};
var jsondata = {
"operator_name": "eee",
"data": [
{
"first_name": "CHaahal"
}
]
};
var payload = JSON.stringify(jsondata);
var url = "http://some_server.com";
var options = {
"method": "POST",
"contentType": "application/json",
"headers": headers,
"payload": payload
};
Logger.log(options);
var response = UrlFetchApp.fetch(url, options);
var responseCode = parseInt(response.getResponseCode());
Logger.log(response);
Logger.log(responseCode);
}
At the server side, I am getting an HTML request instead of json request.
When I hit the same API using Postman with the headers set, the api works. Please suggest
Related
I'm trying to POST some json datas in lua with luasec, but while following examples, it looks like no data is sent. It occurs even with GET requests. Maybe I'm not using ltn12 correctly ?
Here is the code I tried :
local ltn12 = require('ltn12')
local https = require('ssl.https')
local json = require("json")
local body = json.encode({
test = "test ok"
})
local r = {}
https.request {
url = 'https://httpbin.org/anything',
method = "POST",
headers = {["Content-Type"] = "application/json"},
source = ltn12.source.string(body),
sink = ltn12.sink.table(r)
}
print(r[1])
And here's the result :
{
"args": {},
"data": "",
"files": {},
"form": {},
"headers": {
"Content-Type": "application/json",
"Host": "httpbin.org",
"User-Agent": "LuaSocket 3.0-rc1",
"X-Amzn-Trace-Id": "..."
},
"json": null,
"method": "POST",
"origin": "XX.XX.XX.XX",
"url": "https://httpbin.org/anything"
}
The "data" field is empty.
Answering myself, problem solved. It is not a luasec issue, things are similar with socket.http.
The body sent has "content-type: application/json", so the data is in json field, not in data field.
headers needs a size of the datas
So the correct code is :
local ltn12 = require('ltn12')
local https = require('ssl.https')
local json = require("json")
local body = json.encode({
test = "test ok"
})
local r = {}
https.request {
url = 'https://httpbin.org/anything',
method = "POST",
headers = {
["Content-Type"] = "application/json",
["Content-Length"] = #body
},
source = ltn12.source.string(body),
sink = ltn12.sink.table(r)
}
print(r[1])
first way I tried is :
static async callSendApi(requestBody) {
let url = new URL(
`${API_URL}/${PAGE_ID}/messages`
);
url.search = new URLSearchParams({
access_token: `${PAGE_ACCESS_TOKEN}`,
});
console.warn("Request body is\n" + JSON.stringify(requestBody));
let response = await axios.post(url, {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(requestBody),
// access_token: `${PAGE_ACCESS_TOKEN}`,
});
if (!response.ok) {
consoleconst`Unable to call Send API: ${response.statusText}`,
await response.json();
}
}
Second way I tried is :
static async callSendApi(requestBody) {
let url = new URL(
`${API_URL}/${PAGE_ID}/messages?access_token=${PAGE_ACCESS_TOKEN}`
);
/* url.search = new URLSearchParams({
access_token: `${PAGE_ACCESS_TOKEN}`,
});*/
console.warn("Request body is\n" + JSON.stringify(requestBody));
let response = await axios.post(url, {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(requestBody),
// access_token: `${PAGE_ACCESS_TOKEN}`,
});
if (!response.ok) {
consoleconst`Unable to call Send API: ${response.statusText}`,
await response.json();
}
}
the error I get :
error: {
message: 'Unknown path components: /messagesaccess_token=access_token
type: 'OAuthException',
code: 2500,
fbtrace_id: 'AbBJGVotjz3ijKKLzVE6_CM'
}
I'm receiving this error in both ways. both ways are escaping the '?' mark. I have no idea what is happening.. I'm using heroku for this. I tried deleting and redeploying the repository to confirm if the code is not updating. but still gives this error. :( .
I tried withot using URL and URLSearchParams and it worked!
below is my code:
static async callSendApi(requestBody) {
console.warn("Request body is\n" + JSON.stringify(requestBody));
let response = await axios.post(
`${API_URL}/${PAGE_ID}/messages`,
{
params: { access_token: `${PAGE_ACCESS_TOKEN}` },
},
{
headers: { "Content-Type": "application/json" },
body: JSON.stringify(requestBody),
}
);
if (!response.ok) {
consoleconst`Unable to call Send API: ${response.statusText}`,
await response.json();
}
}
This is my code to make the call, a POST. Until now I only needed to send one product in each post.
But, I wanted to start sending my list of products in just one POST.
Future DadosPagamento() async {
await Future.delayed(const Duration(milliseconds: 200));
var headers = {'Authorization': 'Bearer Gns2DfakHnjd9id', 'Content-Type': 'application/json'};
var request = http.Request(
'POST', Uri.parse('http://appdnz.ddns/APP1/Products'));
request.body = json.encode(
[
{
"OrderState": "",
"LineID": "1",
"ClientID": idCliente,
"ProductReference": ref,
"Color": color,
"Size": size,
"Quantity": quantity,
"UnitPriceWithoutTax": precoSemTax,
"ShippingAmount": envioPreco,
"OrderReference": "",
"CarrierID": idTrans,
"Comments": comentario,
"ProductDescription": descricaoProd,
"ShippingName": envioNome,
},
],
);
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
} else {
print(response.reasonPhrase);
}
}
example of what i want to send
request.body = json.encode(
[
{
"Lineid" = "1",
"Reference"= "xpto",
"Quantity"= "1"
....
}
,
{
"Lineid" = "2",
"Reference" = "xpto2",
"Quantity" = "5"
...
}
,
{
"Lineid" = "3",
"Reference" = "xpto3",
"Quantity" = "6"
...
}
]
)
In the research I did, I realized that it might work if I create a list and put it in json.encode(list), I don't know if it's the best way or if there aren't any more ways.
Thanks
This JavaScript Fetch code returns the data I need in Postman. But, I am trying to get this code to work in Google Script Editor for my google sheet, and it is giving me the following error:
ReferenceError: Headers is not defined line 3.
I am brand new to coding, so please bear with me.
Any idea what's wrong here?
POSTMAN CODE:
var myHeaders = new Headers();
myHeaders.append("Content-Type", "text/plain");
var raw = "{\n \"id\": 1,\n \"jsonrpc\": \"1.0\",\n \"method\": \"getbeaconbeststatedetail\",\n \"params\": []\n}";
var requestOptions = {
method: 'GET',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("https://mainnet.incognito.org/fullnode", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
EDIT:
I have tried to update this:
function myFunction() {
var data = {
'request': {
'id': '1',
'jsonrpc': '1.0',
'method': 'getbeaconbeststatedetail',
'params': []
}
};
var payload = JSON.stringify(data);
var options = {
'method' : 'GET',
'headers': { 'Content-Type': "text/plain", 'Accept': "text/plain"},
'muteHttpExceptions': true,
'contentType' : 'application/json',
'body' : payload
};
var url = "https://mainnet.incognito.org/fullnode";
var response = UrlFetchApp.fetch(url, options);
var txt= response.getContentText();
var d=JSON.parse(txt);
var sh1=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet14");
for (let i = 0; i < d.length; i++) {
sh1.getRange(1, 1).setValue(d);
}
}
But, I am still getting the following error:
Exception: Request failed for https://mainnet.incognito.org returned code 400
If you are trying to make an HTTP request from Google Apps Script, you have to use the UrlFetchApp() method.
As #Tanaike points out, GAS is based in JS but not all JS functions are allowed. However GAS does have many services to integrate with G Suite products, and external APIs or services. One very useful service is URL Fetch Service which allows you to perform any type of Http request.
For example:
// Make a GET request with headers.
var options = {
"method" : "GET",
"headers" : {
"Content-Type" : "text/plain",
"API_KEY": "dummydummy"
}
};
var response = UrlFetchApp.fetch("https://api.myawesomeapi.com/get", options);
You can also make POST or other requests. Please refer to the examples in the documentation for use cases.
Update:
You are receiving the 400 "Bad request" error from the "fullnode" endpoint because it requires a POST request with a payload.
function fetchFullNode() {
var url = "https://mainnet.incognito.org/fullnode";
var data = {
"jsonrpc":"1.0",
"method":"getblockchaininfo",
"params":"",
"id":65
};
var options = {
'method' : 'post',
'contentType': 'application/json',
'payload' : JSON.stringify(data)
};
var response = UrlFetchApp.fetch(url, options);
var txt= response.getContentText();
return JSON.parse(txt);
}
I am developing an iOS app using IBM MobileFirst Platform 8.0 sdk that have push notification capabilities
I managed to send notification via postman, the process was
obtaining a token from the MobileFirst platform server
and send the notification via rest api along with the token
The tutorial link i have follow is,
Server Side - https://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/8.0/notifications/sending-notifications/
Client Side - https://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/8.0/notifications/handling-push-notifications/cordova/
Get Token - https://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/8.0/authentication-and-security/confidential-clients/#obtaining-an-access-token
For now, i am trying to send a push notification when the app triggers an adapter call
I am currently stuck on sending the notification using WL.Server.invokeHttp, below is more adapter code
function sendPushNotification(message) {
var result = getToken();
var access_token = "Bearer " + result["access_token"];
var requestStructure = {
method : 'post',
returnedContentType : 'json',
path : '/imfpush/v1/apps/my.app/messages',
headers: {
"Content-Type" : "application/json",
"Authorization" : access_token
},
parameters : {
'message':{'alert' : 'Test message'}
}
};
result = MFP.Server.invokeHttp(requestStructure);
return result;
}
function getToken() {
var requestStructure = {
method : 'post',
returnedContentType : 'json',
path : '/mfp/api/az/v1/token',
headers: {
"Content-Type" : "application/x-www-form-urlencoded",
"Authorization" : "Basic UHVzaE5vd213123asdsadGlvbjpQdXNoTm90aasdasdWZpY2F0aW9u"
},
parameters:{
"grant_type" : "client_credentials",
"scope" : "push.application.my.app messages.write"
}
};
var results = MFP.Server.invokeHttp(requestStructure);
return results;
}
I seems to having issue on
parameters : {
'message':{'alert' : 'Test message'}
}
I might have done it wrongly on this part, do hope for advice.
Thanks in advance
The sendPushNotification method use a wrong syntax for calling WS in Mobile First.
you cloud change it like this:
function sendPushNotification(message) {
var result = getToken();
var access_token = "Bearer " + result["access_token"];
var requestStructure = {
method : 'post',
returnedContentType : 'json',
path : '/imfpush/v1/apps/my.app/messages',
headers: {
"Authorization" : access_token
},
body: {
content: 'message':{'alert' : 'Test message'},
contentType: 'application/json'
}
};
result = MFP.Server.invokeHttp(requestStructure);
return result;
}