I am writing a http client in lua to consume a rest web service.
The webservice result should be in this json format:
{
"code": "123456789",
"valid_until": "09/09/2020"
}
This is my lua script:
param_1 = arg[1];
param_2 = arg[2];
http = require("socket.http");
ltn12 = require("ltn12");
path = "http://www.url.com:8080/api/";
body = [[ {"number_id":"b8ce37fb-2061-4aea-975b-57a8e2d355ce","param_1":"]]..param_1..[[","param_2":"]]..param_2..[["} ]];
response_body = { }
res, code, response_haders, status = http.request {
url = path,
method = "POST",
headers =
{
["X-Access-Key"] = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
["Content-Type"] = "application/json",
["Content-Length"] = body:len()
},
source = ltn12.source.string(body),
}
print("res:"..res);
print("code:"..code);
print("status:"..status);
when I run my script this is the results I got:
res:1
code:201
statusHTTP/1.0 201 CREATED
Why I getting 1 as result, What should I do to parse the result?
Related
python codes get response but javascript code can't get response.
what is diff between the two??
import fetch from 'node-fetch';
const url = "http://host3.dreamhack.games:15592/img_viewer"
const imageUrl = "/static/dream.png"
const data = {
"url": imageUrl
}
const res = await fetch(url, {
method: "POST",
body: JSON.stringify(data)
})
const text = await res.text()
console.log(text)
//<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
//<title>500 Internal Server Error</title>
//<h1>Internal Server Error</h1>
//<p>The server encountered an internal error and was unable to complete your request. Either the //server is overloaded or there is an error in the application.</p>
import requests
url = "http://host3.dreamhack.games:15592/img_viewer"
imageUrl = "/static/dream.png"
data = {
"url": imageUrl
}
response = requests.post(url, data=data)
print(response.text)
I think the two codes are same, why get different response?
(after time above url is not available)
** server
#app.route("/img_viewer", methods=["GET", "POST"])
def img_viewer():
if request.method == "GET":
return render_template("img_viewer.html")
elif request.method == "POST":
url = request.form.get("url", "")
urlp = urlparse(url)
if url[0] == "/":
url = "http://localhost:8000" + url
elif ("localhost" in urlp.netloc) or ("127.0.0.1" in urlp.netloc):
data = open("error.png", "rb").read()
img = base64.b64encode(data).decode("utf8")
return render_template("img_viewer.html", img=img)
try:
data = requests.get(url, timeout=3).content
img = base64.b64encode(data).decode("utf8")
except:
data = open("error.png", "rb").read()
img = base64.b64encode(data).decode("utf8")
return render_template("img_viewer.html", img=img)
I see 2 reasons:
The headers in node-js might be drifferent by default. You could specify them to make the requests identical tho.
It seems like javascript has a different fingerprint than python-requests, even when using the same headers. Some websites like cloudfare can detect that, and then usually throw a 403 [Forbidden] http error.
But I didn't find out, what exactly is defferent that case.
I'm attempting to setup a simple Siddhi flow where I receive a message using an http listener, use a field from that message as an input to an http API call, then log the result.
The problem I'm having is I cannot seem to get basic http authentication to work on the API call. It seems to just not send an Authorization header. Here is the Siddhi flow I built:
#App:name('Test Flow')
#App:description('Listen, call, log')
#source(type = 'http', receiver.url = "http://0.0.0.0:8007/myListener",
#map(type = 'json',
#attributes(someInputField = "$.someInputField")))
#sink(type = 'http-call', publisher.url = "https://somehost.com/someApiPath", sink.id = "callAPI.sink", basic.auth.username = "testUser", basic.auth.password = "testPass", https.truststore.file = "/usr/local/ssl/keystore.jks", https.truststore.password = "someTruststorePass", headers = "'Content-Type: application/json'", method = "POST", hostname.verification.enabled = "true",
#map(type = 'json',
#payload(""" { "someStandardPayloadField: "abc", "someInputField": "{{someInputField}}" } """)))
define stream APIStream (someInputField string);
#source(type = 'http-call-response', sink.id = "callAPI.sink", http.status.code = "200",
#map(type = 'json', enclosing.element = "$.outputs",
#attributes(someResponseField = "someOutputfield")))
#sink(type = 'log', prefix = "LOGGER")
define stream logStream (someResponseField string);
I'm using Swift 5 and attempting to get an access token from an API I'm developing using asp.net MVC. With Postman I set my request to GET, pass in some information in the body, and I get back an access token.
In XCode when I try this it gives me the error: "GET method must not have a body."
My Code:
func GetToken(email: String, password: String) {
let dataToSend = [
"grant_type": "password",
"username": email,
"password": password
]
let newData = try! JSONSerialization.data(withJSONObject: dataToSend, options: [])
var request = URLRequest(url: getNewTokenURL)
request.httpMethod = "Get"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = newData
URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let data = data else {return}
do {
let myData = try JSONDecoder().decode(TokenResponse.self, from: data)
self.userToken = myData.accessToken
}
catch {
}
}.resume()
}
How do I perform the GET request with the data I need to send to it?
GET requests don't have a body. Parameters in a GET request are passed along with it's url as query parameters.
let url = URL(string: "https://www.example.com/getExample?sampleParam=sampleValue&anotherParam=anotherValue")
Edit: Also you need to give method in all caps. Since GET is the default you didn't have an issue.
Also if you are sure that the data is being passed as JSON then the method should be a POST method for that you just need to set the method of the request to POST as follows:
request.method = "POST"
Note: It's case sensitive.
CURRENTLY
I am utilising WooCommerce REST API in my Google Scripts with the following working code:
var ck = "ck_longstringlongstringlongstringlongstring";
var cs = "cs_longstringlongstringlongstringlongstring";
var website = "https://www.mywebsite.com.au";
var url = website + "/wp-json/wc/v3/orders?consumer_key=" + ck + "&consumer_secret=" + cs;
var options =
{
"method": "GET",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"muteHttpExceptions": true,
};
var result = UrlFetchApp.fetch(url, options);
PROBLEM
To improve security, I want to put consumer key and secret into the header, but I cannot get the following script to work
var url = website + "/wp-json/wc/v3/orders;
let authHeader = 'Basic ' + Utilities.base64Encode(ck + ':' + cs);
var options =
{
"method": "GET",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"muteHttpExceptions": true,
"headers": {"Authorization": authHeader},
};
var result = UrlFetchApp.fetch(url, options);
Current result = {"code":"woocommerce_rest_cannot_view","message":"Sorry, you cannot list resources.","data":{"status":401}}
Expected result = JSON of orders
Is it an issue with my code? Or with WooCommerce API or Google Scripts?
There are a few issues with your code.
With UrlFetchApp.fetch() you need to use contentType instead of Content-Type.
However, in this case you don't even need to set it since application/x-www-form-urlencoded is the default. Same goes for the method property; it defaults to GET.
Moreover, if you want to err on the side of caution use Utilities.base64EncodeWebSafe(data, charset) to base64 encode your credentials instead of the non-web-safe version.
let url = website + "/wp-json/wc/v3/orders";
let encoded = Utilities.base64EncodeWebSafe(ck + ':' + cs, Utilities.Charset.UTF_8);
let options = {
"muteHttpExceptions":true,
"headers": {
"Authorization": "Basic " + encoded
}
};
let result = UrlFetchApp.fetch(url, options);
result = JSON.parse(result);
I need to log in example.com/mobile/shared/default.aspx by using POST request
How do i get current ViewState and sending it after?
That is what i tried
(Alamofire)
func webRequest()
{
let parameters: Parameters = [
"name": "name",
"password": "password",
"enter": "Enter",
]
Alamofire.request("http://example.ru/mobile/shared/default.aspx", parameters: parameters).responseJSON { response in
print(response.request) // original URL request
print(response.response) // HTTP URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
}
I'm using Alamofire like this:
let Parameters = [
"name": "name",
"password": "password",
"enter": "Enter"]
var json : JSON = nil
Alamofire.request(URLString, method: method, parameters: Parameters)
.responseJSON { response in
switch response.result {
case .success(let data):
json = JSON(data)
print(json)
case .failure(let error):
print("Request failed with error: \(error)")
}
}
}
So after that you can parse your json like this for example:
if json != nil {
let token = json["token"].stringValue
}
But all of that depend of your server request params, and request response from your server.
Hope I helped you, Peace