I'm trying to post json in Lua using cURL. I can't find any example online.
Something like this:
c = curl.easy{
url = "http://posttestserver.com/post.php",
-- url = "http://httpbin.org/post",
post = true,
httppost = curl.form{
data = "{}",
type = "application/json",
},
}
t = {}
c:perform{
writefunction = function(s)
t[#t+1] = s
end
}
c:close()
Try this one.
local cURL = require "cURL"
c = cURL.easy{
url = "http://posttestserver.com/post.php",
post = true,
httpheader = {
"Content-Type: application/json";
};
postfields = "{}";
}
c:perform()
Related
I am trying to place an order but it gives me this error:
{"code":"400005","msg":"Invalid KC-API-SIGN"}
I'll be so thankful if someone check my code and let me know the problem
import requests
import time
import base64
import hashlib
import hmac
import json
import uuid
api_key = 'XXXXXXXXXXXXXXXXXXXXXXX'
api_secret = 'XXXXXXXXXXXXXXXXXXXXXX'
api_passphrase = 'XXXXXXXXXXXXXXX'
future_base_url = "https://api-futures.kucoin.com"
clientOid = uuid.uuid4().hex
params = {
"clientOid": str(clientOid),
"side": str(side),
"symbol": str(symbol),
"type": "limit",
"leverage": "5",
"stop": "down",
"stopPriceType": "TP",
"price": str(price),
"size": int(size),
"stopPrice": str(stopprice)
}
json_params = json.dumps(params)
print(json_params)
now = int(time.time() * 1000)
str_to_sign = str(now) + 'POST' + '/api/v1/orders' + json_params
signature = base64.b64encode(hmac.new(api_secret.encode('utf-8'), str_to_sign.encode('utf-8'), hashlib.sha256).digest())
passphrase = base64.b64encode(hmac.new(api_secret.encode('utf-8'), api_passphrase.encode('utf-8'), hashlib.sha256).digest())
headers = {
"KC-API-SIGN": signature,
"KC-API-TIMESTAMP": str(now),
"KC-API-KEY": api_key,
"KC-API-PASSPHRASE": passphrase,
"KC-API-KEY-VERSION": "2",
"Content-Type": "application/json"
}
response = requests.request('POST', future_base_url + '/api/v1/orders', params=params, headers=headers)
print(response.text)
This worked for me:
tickerK = "AVAXUSDTM"
clientOid = tickerK + '_' + str(now)
side = "buy"
typee = "market"
leverage = "2"
stop = "up"
stopPriceType = "TP"
stopPrice = "12"
size = "3"
# Set the request body
data = {
"clientOid":clientOid,
"side":side,
"symbol":tickerK,
"type":typee,
"leverage":leverage,
"stop":stop,
"stopPriceType":stopPriceType,
"stopPrice":stopPrice,
"size":size
}
data_json = json.dumps(data, separators=(',', ':'))
data_json
url = 'https://api-futures.kucoin.com/api/v1/orders'
now = int(time() * 1000)
str_to_sign = str(now) + 'POST' + '/api/v1/orders' + data_json
signature = base64.b64encode(
hmac.new(api_secret.encode('utf-8'), str_to_sign.encode('utf-8'), hashlib.sha256).digest())
passphrase = base64.b64encode(hmac.new(api_secret.encode('utf-8'), api_passphrase.encode('utf-8'), hashlib.sha256).digest())
headers = {
"KC-API-SIGN": signature,
"KC-API-TIMESTAMP": str(now),
"KC-API-KEY": api_key,
"KC-API-PASSPHRASE": passphrase,
"KC-API-KEY-VERSION": "2",
"Content-Type": "application/json"
}
# Send the POST request
response = requests.request('post', url, headers=headers, data=data_json)
# Print the response
print(response.json())
Please take care of the lines marked in red:
Remove spaces from the json
Add the json to the string to sign
Add content type to the header
Do the request this way
I want to make api calls using json object request in android studio using kotlin.
This is the api.
How to access the 'name' in the array articles ?. I can access all the other things except 'id' and 'name'.
This is my code
val url = "https://news-api-don.herokuapp.com/api/v1?apiKey=20d14506791144cc8b424549c42068c0"
val jsonObjectRequest = JsonObjectRequest(
Request.Method.GET, url, null,
{
val newsJsonArray = it.getJSONArray("articles")
val newsArray = ArrayList<News>()
for(i in 0 until newsJsonArray.length()) {
val newsJsonObject = newsJsonArray.getJSONObject(i)
val news = News(
newsJsonObject.getString("title"),
newsJsonObject.getString("author"),
newsJsonObject.getString("url"),
newsJsonObject.getString("urlToImage")
)
newsArray.add(news)
}
mAdapter.updateNews(newsArray)
swipeRefreshLayout.isRefreshing = false
progressBar.visibility = View.GONE
},
{
Toast.makeText(this,"Something went wrong", Toast.LENGTH_LONG).show()
swipeRefreshLayout.isRefreshing = false
progressBar.visibility = View.GONE
}
)
MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest)
}
I'm new to LUA and tried learning coding this language with Garrys Mod.
I want to get the messages from the Garrys Mod chat and send them into a Discord channel with a webhook.
It works, but I tried expanding this project with embeded messages. I need JSON for this and used json.lua as a library.
But as soon as I send a message I retrieve the following error message:
attempt to index global 'json' (a nil value)
The code that causes the error is the following:
json.encode({ {
["embeds"] = {
["description"] = text,
["author"] = {
["name"] = ply:Nick()
},
},
} }),
The complete code:
AddCSLuaFile()
json = require("json")
webhookURL = "https://discordapp.com/api/webhooks/XXX"
local DiscordWebhook = DiscordWebhook or {}
hook.Add( "PlayerSay", "SendMsg", function( ply, text )
t_post = {
content = json.encode({ {
["embeds"] = {
["description"] = text,
["author"] = {
["name"] = ply:Nick()
},
},
} }),
username = "Log",
}
http.Post(webhookURL, t_post)
end )
I hope somebody can help me
Garry's Mod does provide two functions to work with json.
They are:
util.TableToJSON( table table, boolean prettyPrint=false )
and
util.JSONToTable( string json )
There is no need to import json and if I recall correctly it isn't even possible.
For what you want to do you need to build your arguments as a table like this:
local arguments = {
["key"] = "Some value",
["42"] = "Not always the answer",
["deeper"] = {
["my_age"] = 22,
["my_name"] = getMyName()
},
["even more"] = from_some_variable
and then call
local args_as_json = util.TableToJSON(arguments)
Now you can pass args_as_json to your
http.Post( string url, table parameters, function onSuccess=nil, function onFailure=nil, table headers={} )
I'm able to read a data from Motion Controller with HTTP in MATLAB .
Request code in MATLAB...
api = 'http://192.168.0.105';
url = [api 'kas/plcvariables?variables=Velocity&format=text'];
options = weboptions('ContentType', text);
data = webread(url, options);
But, I can't write to the Motion Controller in MATLAB, with data format "text" or "json", it does not matter. How can I write to the Motion Controller?
Writing format in json
PUT http://198.51.100.0/kas/plcvariables?format=json { "MachineSpeed"
: {"value" : "100.000000"}, " IntegerVar " : {"value" : "20"},
“UntitledST.LocalVariable” : {"value" : "’SampleString’”} }
in text
PUT http://198.51.100.0/kas/plcvariables?format=text
MachineSpeed=100.000000,IntegerVar=20,UntitledST.LocalVariable=’SampleString’
I tried some code in Matlab, and the last one is below.
api = 'http://192.168.0.105';
url = [api 'kas/plcvariables?'];
ab = struct('value', '10000.00');
data.V = {ab};
options = webopitons('MediaType', 'application/json',
'RequestMethod', 'POST', 'ContentType', 'json');
response = webwrite(url, data, options);
But all of them gave the same errors that are below.
Error using readContentFromWebService (line 45) The server returned the message: "Not Found" for URL, 'http://192.168.0.105/kas/plcvariables?' (with HTTP response code 404).
I think I dont know the right URL address, Can you help me how I can write the right URL address for motion controller?
I figure out where I'm wrong with the help of Martin (kollmorgen.com/en-us/developer-network/…). I share code for anybody who may need this with link above and code as below
int main() {
CURLcode ret;
CURL *curl_easy_handle;
curl_global_init(CURL_GLOBAL_ALL);
std::string jsonstr = "{\"Position\" : {\"value\" : \"4000\"}}";
struct curl_slist *headers;
headers = curl_slist_append(headers, "Content-Type: application/json");
headers = curl_slist_append(headers, "Accept: application/json");
headers = curl_slist_append(headers, "charset: utf-8");
curl_easy_handle = curl_easy_init();
if (curl_easy_handle == NULL) {
return 128;
}
curl_easy_setopt(curl_easy_handle, CURLOPT_URL, "http://192.168.0.105/kas/plcvariables?format=json");
curl_easy_setopt(curl_easy_handle, CURLOPT_CUSTOMREQUEST, "PUT");
curl_easy_setopt(curl_easy_handle, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl_easy_handle, CURLOPT_POSTFIELDS, jsonstr.c_str());
curl_easy_setopt(curl_easy_handle, CURLOPT_USERAGENT, "libcrp/0.1");
ret = curl_easy_perform(curl_easy_handle);
curl_easy_cleanup(curl_easy_handle);
curl_global_cleanup();
curl_easy_handle = NULL;
curl_slist_free_all(headers);
headers = NULL;
}
I have 2 query results from the database and try to return it in json format like this.
gt_buffer = ev_ground_truth.objects.filter(alg=_alg, exp=_exp,nFrame=_nframe)
dt_buffer = ev_detection.objects.filter(alg = _alg, exp=_exp, nFrame=_nframe)
json_gt_bb = serializers.serialize('json', gt_buffer)
json_dt_bb = serializers.serialize('json', dt_buffer)
dict_bb_buffer = {'gt': json_gt_bb, 'dt': json_dt_bb}
json_bb_buffer = json.dumps(dict_bb_buffer, ensure_ascii=False)
return HttpResponse(dict_bb_buffer, content_type = "application/json")
And at the front-end,
$.ajax({
url: '/results/get_nframebbs',
data: {
'exp':_exp,
'alg':_alg,
'nframe':data[i]['fields'].nFrame
},
dataType: 'json',
success: function (data) {
alert(data.length)
}
});
However the alert never be called. But if I just serialize 1 query result and return the alert is called successful with a popup.
gt_buffer = ev_ground_truth.objects.filter(alg=_alg, exp=_exp,nFrame=_nframe)
json_gt_bb = serializers.serialize('json', gt_buffer)
return HttpResponse(json_gt_bb, content_type = "application/json")
What did I do wrong?
You have the response as an argument in your success function, not the json data directly. you can access to your data like this:
success: function (response) {
var gt = response.responseJSON.gt;
}
Easy. Just return 2 query result as string and parse at the front-end.
gt_buffer = ev_ground_truth.objects.filter(alg=_alg, exp=_exp,nFrame=_nframe)
dt_buffer = ev_detection.objects.filter(alg = _alg, exp=_exp, nFrame=_nframe)
json_gt_bb = serializers.serialize('json', gt_buffer)
json_dt_bb = serializers.serialize('json', dt_buffer)
dict_bb_buffer = {'gt': json_gt_bb, 'dt': json_dt_bb}
return JsonResponse(dict_bb_buffer, status = 201)
and at the front-end:
dataType: 'json',
success: function (data) {
gt = JSON.parse(data.gt.substring(1,data.gt.length-1));
dt = JSON.parse(data.dt.substring(1,data.dt.length-1));
}