POST in ixwebsocket fail - ssl

I have the following curl works fine:
curl -H "X-MBX-APIKEY: XXXXXXXXXXXXXXXXXXXXX" -X POST "https://testnet.binancefuture.com/fapi/v1/order?symbol=BTCUSDT&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=21002.2&recvWindow=60000&timestamp=1676439415772&signature=28ba85cfdb2b44cf12d89281c6ef7704a4211224b6b92c81763ec394b2e8db87"
https://github.com/machinezone/IXWebSocket
I download ixwebsocket and build it in my linux server
and try to make a post request refer to the following :
https://machinezone.github.io/IXWebSocket/usage/#http-client-api
here is my test source :
string req="https://testnet.binancefuture.com/fapi/v1/order?symbol=BTCUSDT&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=21002.2&recvWindow=60000&timestamp=1676439415772&signature=28ba85cfdb2b44cf12d89281c6ef7704a4211224b6b92c81763ec394b2e8db87" ;
HttpClient httpClient;
HttpRequestArgsPtr args = httpClient.createRequest();
WebSocketHttpHeaders headers;
headers["X-MBX-APIKEY"] = "XXXXXXXXXXXXXXXXXXXXX";
args->extraHeaders = headers;
HttpResponsePtr response;
std::string ixurl = "https://testnet.binancefuture.com";
//response = httpClient.request(ixurl, "POST",req, args,0);
response = httpClient.post(ixurl, req, args);
auto body = response->body;
cout << body << endl ;
This source cause dump , after search ixwebsocket website , I still can not figure out what went wrong , any advice,comments are most appreciated .

Related

Consume tensor-flow serving inception model using C# client (PREDICT API)

I have been trying to implement a C# client application to interact with Tensorflow serving server for few weeks now with no success. I have a Python client which works successfully but I can not replicate its functionality with C#. The Python client
import requests
#import json
from keras.preprocessing.image import img_to_array, array_to_img, load_img
from keras.preprocessing import image
flowers = 'c:/flower_photos/cars/car1.jpg'
image1 = img_to_array(image.load_img(flowers, target_size=(128,128))) / 255
payload = {
"instances": [{"image":image1.tolist()},
]
}
print("sending request...")
r = requests.post('http://localhost:8501/v1/models/flowers/versions/1:predict', json=payload)
print(r.content)
The server responds correctly. I am using Tensorflow version 1.12.0 with corresponding latest serving image. They are all working fine.
According to REST API documentation, the API structure is given but its not clear to me at all. I need to send the image to server. How could I add the image payload to JSON request in C# ? After going through many sites, I found that image should be in base64string.
So I did the image conversion into base64
private string GetBase64ImageBytes(string ImagePath)
{
using (Image image = Image.FromFile(ImagePath))
{
using (MemoryStream m = new MemoryStream())
{
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
}
The request portion is as follows : (server responds with metadata correctly for the GET request)
public string PostImageToServerAndClassify(string imageArray)
{
//https://stackoverflow.com/questions/9145667/how-to-post-json-to-a-server-using-c
string result = null;
string ModelName = cmbProjectNames.Text.Replace(" ", "");
string status_url = String.Format("http://localhost:{0}/v1/models/{1}/versions/{2}:predict", txtPort.Text, ModelName, txtVersion.Text);
var httpWebRequest = (HttpWebRequest)WebRequest.Create(status_url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
try
{
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
// string json = "{"+ #"""instances""" + ": [{" + #"""image""" + #":" + imageArray + "}]}";
// imageArray = #""" + imageArray + #""";
string json = "{ " + #"""instances""" + ": [{" + #"""image""" + #": { " + #"""b64"": """ + imageArray + #"""}}]}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
}
catch (Exception ex)
{
result = ex.Message;
}
return result;
}
With the POST request, I get the error message "The remote server returned an error: (400) Bad Request.". Also server terminates its service. In Postman I get
the detailed error info as :
{ "error": "Failed to process element: 0 key: image of \'instances\' list. Error: Invalid argument: JSON Value: {\n \"b64\": \"/9j/4AAQSkZJRgABAQEAAAAAAAD/4QBSRXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAZKGAAcAAAAcAAAALAAAAABVTklDT0RFAABBAHAAcABsAGUATQBhAHIAaw ... .....(image string data)
So this feels like that I am sending the incorrect data format.
Could someone please tell me what is wrong here ? Any example of image conversion and POST request is highly appreciated. I can not find anywhere that base64string format is the right format for the image in TF site. Python client data format is different hence really need to know what is the right format with any reference documents.
The nearest reference I found here with JAVA client but did not work with mine may be due to TF version difference.

How to query REST API

I am using this code below to deal with the REST API query for Adobe Analytics. I always get the message "something went wrong" which means that the first IF is not active.
include_once('/path/SimpleRestClient.php');
$username = 'XXXXX';
$secret = 'XXXXX';
$nonce = md5(uniqid(php_uname('n'), true));
$nonce_ts = date('c');
$digest = base64_encode(sha1($nonce.$nonce_ts.$secret));
$server = "https://api.omniture.com";
$path = "/admin/1.4/rest/";
$rc=new SimpleRestClient();
$rc->setOption(CURLOPT_HTTPHEADER, array("X-WSSE: UsernameToken Username=\"$username\", PasswordDigest=\"$digest\", Nonce=\"$nonce\", Created=\"$nonce_ts\""));
$query="?method=Company.GetTokenUsage";
$rc->getWebRequest($server.$path.$query);
if ($rc->getStatusCode()==200)
{
$response=$rc->getWebResponse();
var_dump($response);
}
else
{
echo "something went wrong\n";
var_dump($rc->getInfo());
}
The $rc->getStatusCode(); does not exit. I get '404' when I use this line :
print_r ($rc->getStatusCode());
After googling, I found https://marketing.adobe.com/developer/blog/how-to-start-with-the-omniture-rest-api-in-php. It uses API version of 1.3 instead of 1.4. By updating the
$path = "/admin/1.4/rest/";
to
$path = "/admin/1.3/rest/";
I was able to stop getting 404 errors in the browser.

How do I set http headers in Adobe Illustrator ExtendScript when using the BridgeTalk HttpConnection object?

I am trying to make http post requests from within Illustrator ExtendScript (via BridgeTalk) and for the most part it is working. However, the documentation on using HttpConnection is non-existent and I am trying to figure out how to set http-headers. The HttpConnection object has both a requestheaders and responseheaders property so I suspect it is possible.
By default, the post requests are being sent with the Content-Type header "text/html", and I would like to override it so that I can use either "application/x-www-form-urlencoded" or "multipart/form-data".
Here is what I have so far:
var http = function (callback) {
var bt = new BridgeTalk();
bt.target = 'bridge' ;
var s = '';
s += "if ( !ExternalObject.webaccesslib ) {\n";
s += " ExternalObject.webaccesslib = new ExternalObject('lib:webaccesslib');\n";
s += "}\n";
s += "var html = '';\n";
s += "var http = new HttpConnection('http://requestb.in/1mo0r1z1');\n";
s += "http.method = 'POST';\n";
s += "http.requestheaders = 'Content-Type, application/x-www-form-urlencoded'\n";
s += "http.request = 'abc=123&def=456';\n";
s += "var c=0,t='';for(var i in http){t+=(i+':'+http[i]+'***');c++;}t='BEFORE('+c+'):'+t;alert(t);\n"; // Debug: to see what properties and values exist on the http object
s += "http.response = html;\n";
s += "http.execute() ;\n";
s += "http.response;\n";
s += "var t='AFTER:';for(var i in http){t+=(i+':'+http[i]+'***');}alert(t);\n"; // Debug: to see what properties and values have been set after executing
bt.body = s;
bt.onResult = function (evt) {
callback(evt);
};
bt.onError = function (evt) {
callback(evt);
};
bt.send();
};
Things to note:
If I try setting the requestheaders properties like in my code above, the request fails. If I comment it out, the request succeeds. The default value for requestheaders is undefined.
Examining the http object after a successful request, shows the reponseheaders properties to be set to: "Connection, keep-alive,Content-Length, 2,Content-Type, text/html; charset=utf-8,Date, Wed, 24 Jun 2015 09:45:40 GMT,Server, gunicorn/18.0,Sponsored-By, https://www.runscope.com,Via, 1.1 vegur". Before the request executes, the responseheaders is set to undefined.
If anyone could help me set the request headers (in particular the Content-Type header), I would be eternally grateful!
Solved it!
The key for setting the content-type header is to set the http.mime property as follows:
s += "http.mime = 'application/x-www-form-urlencoded';\n";
Also for completeness, you can add your own custom headers as follows:
s += "http.requestheaders = ['My-Sample-Header', 'some-value'];\n";
(It turns out the headers is an array which takes the format [key1, value1, key2, value2, .......])

i am having a issue with json codeigniter rest its not closing the tag

i am having a problem with json codeigniter rest
i am making this call to the server and the problem its that its not closing the json tags
s, USA","clientUID":"7","email":null,"idipad":"2","dateModified":null},{"id":"19","uid":null,"name":"Wayne Corporation, Inc.","phone":"932345324","address":"Second st. 312, Gotham City","clientUID":"7","email":"waynecorp#gmail.com","idipad":"1","dateModified":null}]
its missing the final }
this is the code that creates the response :
$this->response(array('login'=>'login success!','user_admin_id'=>$user_id,'client'=>$client,'users'=>$users,'projects'=>$projects,'plans'=>$plans,'meetings'=>$meetings,'demands'=>$demands,'tasks'=>$tasks,'presences'=>$presences,'contractors'=>$contractors,'companies'=>$companies), 200);
this is the client call using curl :
$this->curl->create('http://dev.onplans.ch/onplans/index.php/api/example/login/format/json');
// Option & Options
$this->curl->option(CURLOPT_BUFFERSIZE, 10);
$this->curl->options(array(CURLOPT_BUFFERSIZE => 10));
// More human looking options
$this->curl->option('buffersize', 10);
// Login to HTTP user authentication
$this->curl->http_login('admin', '1234');
// Post - If you do not use post, it will just run a GET request
//$post = array('remember'=>'true','email'=>'admin.architect#onplans.ch','password'=>'password');
$post = array('remember'=>'true','email'=>'admin.architect#onplans.ch','password'=>'password');
$this->curl->post($post);
// Cookies - If you do not use post, it will just run a GET request
$vars = array('remember'=>'true','email'=>'manuel#ffff.com','password'=>'password');
$this->curl->set_cookies($vars);
// Proxy - Request the page through a proxy server
// Port is optional, defaults to 80
//$this->curl->proxy('http://example.com', 1080);
//$this->curl->proxy('http://example.com');
// Proxy login
//$this->curl->proxy_login('username', 'password');
// Execute - returns responce
echo $this->curl->execute();
// Debug data ------------------------------------------------
// Errors
$this->curl->error_code; // int
$this->curl->error_string;
print_r('error :::::LOGINN REMOTE:::::'.$this->curl->error_string);
// Information
$this->curl->info; // array
print_r('info :::::::::::::'.$this->curl->info);
the response belong to the rest api codeigniter from phil
/**
* Response
*
* Takes pure data and optionally a status code, then creates the response.
*
* #param array $data
* #param null|int $http_code
*/
public function response($data = array(), $http_code = null)
{
global $CFG;
// If data is empty and not code provide, error and bail
if (empty($data) && $http_code === null)
{
$http_code = 404;
// create the output variable here in the case of $this->response(array());
$output = NULL;
}
// If data is empty but http code provided, keep the output empty
else if (empty($data) && is_numeric($http_code))
{
$output = NULL;
}
// Otherwise (if no data but 200 provided) or some data, carry on camping!
else
{
// Is compression requested?
if ($CFG->item('compress_output') === TRUE && $this->_zlib_oc == FALSE)
{
if (extension_loaded('zlib'))
{
if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) AND strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE)
{
ob_start('ob_gzhandler');
}
}
}
is_numeric($http_code) OR $http_code = 200;
// If the format method exists, call and return the output in that format
if (method_exists($this, '_format_'.$this->response->format))
{
// Set the correct format header
header('Content-Type: '.$this->_supported_formats[$this->response->format]);
$output = $this->{'_format_'.$this->response->format}($data);
}
// If the format method exists, call and return the output in that format
elseif (method_exists($this->format, 'to_'.$this->response->format))
{
// Set the correct format header
header('Content-Type: '.$this->_supported_formats[$this->response->format]);
$output = $this->format->factory($data)->{'to_'.$this->response->format}();
}
// Format not supported, output directly
else
{
$output = $data;
}
}
header('HTTP/1.1: ' . $http_code);
header('Status: ' . $http_code);
// If zlib.output_compression is enabled it will compress the output,
// but it will not modify the content-length header to compensate for
// the reduction, causing the browser to hang waiting for more data.
// We'll just skip content-length in those cases.
if ( ! $this->_zlib_oc && ! $CFG->item('compress_output'))
{
header('Content-Length: ' . strlen($output));
}
exit($output);
}
This answer was referenced from Github issue. Also raised by Pedro Dinis, i guest.
I met this problem today and take me long hours to search for the solution. I share here with hope to help someone like me.
The key is to replace around line 430 in the library file: REST_Controller.php :
header('Content-Length: ' . strlen($output));
by
header('Content-Length: ' . strlen("'".$output."'"));
UPDATE: The problem was solved here
Or you can just comment out the code, it will run fine. :)

Why do I get HTTP 401 Unauthorized from my call the to Yahoo contacts API?

This is driving me crackers. I'm implementing a friend invite scheme on a website and need access to the user's Yahoo contacts list. To do this, I'm using OAuth and the yahoo REST api. Here's a complete rundown of the sequence of events:
I have a project set up on developers.yahoo.com which is configured to have read access to Contacts. It's on a made-up domain which I point to 127.0.0.1 in my hosts file (On the off-chance that localhost was causing my woes). For this reason, the domain is not verified though my understanding is that this simply means I have less restrictions, not more.
Firstly, on the server I get a request token:
https://api.login.yahoo.com/oauth/v2/get_request_token
?oauth_callback=http%3A%2F%2Fdev.mysite.com%2Fcallback.aspx
&oauth_consumer_key=MYCONSUMERKEY--
&oauth_nonce=xmaf8ol87uxwkxij
&oauth_signature=WyWWIsjN1ANeiRpZxa73XBqZ2tQ%3D
&oauth_signature_method=HMAC-SHA1
&oauth_timestamp=1328796736
&oauth_version=1.0
Which returns with (Formatted for vague attempt at clarity):
oauth_token=hxcsqgj
&oauth_token_secret=18d01302348049830942830942630be6bee5
&oauth_expires_in=3600
&xoauth_request_auth_url
=https%3A%2F%2Fapi.login.yahoo.com%2Foauth%2Fv2%2Frequest_auth
%3Foauth_token%3Dhxcsqgj
&oauth_callback_confirmed=true"
I then pop-up the xoauth_request_auth_url page to the user and receive a verifier code to my callback page. I then send that back to my server so that I can exchange it for an access token:
https://api.login.yahoo.com/oauth/v2/get_token
?oauth_consumer_key=MYCONSUMERKEY--
&oauth_nonce=yxhd1nymwd03x189
&oauth_signature=c%2F6GTcybGJSQi4TOpvueLUO%2Fgrs%3D
&oauth_signature_method=HMAC-SHA1
&oauth_timestamp=1328796878
&oauth_token=hxcqgjs
&oauth_verifier=b8ngvp <- verifier given via callback
&oauth_version=1.0
That seems to work, and I get an access token back:
oauth_token=MYVERYLONGACCESSTOKEN--
&oauth_token_secret=MYOATHTOKENSECRET
&oauth_expires_in=3600
&oauth_session_handle=ADuXM093mTB4bgJPKby2lWeKvzrabvCrmjuAfrmA6mh5lEZUIin6
&oauth_authorization_expires_in=818686769
&xoauth_yahoo_guid=MYYAHOOGUID
I then immediately attempt to get the contacts list with the access token and the GUID:
http://social.yahooapis.com/v1/user/MYYAHOOGUID/contacts
(HTTP Header added and formatted with line breaks for clarity...)
Authorization: OAuth
realm="yahooapis.com",
oauth_consumer_key="MYCONSUMERKEY--",
oauth_nonce="nzffzj5v82mgf4mx",
oauth_signature="moVJywesuGaPN5YHYKqra4T2ips%3D",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1328796907",
oauth_token="MYVERYLONGACCESSTOKEN--",
oauth_version="1.0"
From this call I get a 401 Unauthorized, but it seems impossible to find out why. To sign these calls, I'm using this oath lib on github. I don't think it's doing anything extraordinary or incompatable. For the signature, I'm including the consumer key/secret and the access token/secret. I've looked at the signature base that's being hashed and it looks to be the same form as the examples visible on yahoo's documentation. I'm guessing that I'm missing something from the parameters that isn't being hashed. Is there a way to find out why the call is unauthorized, or does anyone know of an example showing exactly what form the signature base and authorization header must take?
Solved this myself. Adding the answer just in case it happens to help anyone who makes the same silly mistake I did. When I made the API call, I was using the token secret returned from the original request token call instead of the new one returned from the access token call.
Oops.
this is the code with which I solved, the trusted code to use if yahooapis returns 403 forbidden:
Reference:
https://developer.yahoo.com/yql/guide/yql-code-examples.html#yql_php
https://github.com/danzisi/YQLQueryYahooapis
init CODE
/**
* Call the Yahoo Contact API
*
* https://developer.yahoo.com/yql/guide/yql-code-examples.html#yql_php
*
* #param string $consumer_key obtained when you registered your app
* #param string $consumer_secret obtained when you registered your app
* #param string $guid obtained from getacctok
* #param string $access_token obtained from getacctok
* #param string $access_token_secret obtained from getacctok
* #param bool $usePost use HTTP POST instead of GET
* #param bool $passOAuthInHeader pass the OAuth credentials in HTTP header
* #return response string with token or empty array on error
*/
function call_yql($consumer_key, $consumer_secret, $querynum, $access_token, $access_token_secret, $oauth_session_handle, $usePost=false, $passOAuthInHeader = true){
global $godebug;
$response = array();
if ($consumer_key=='' || $consumer_secret=='' || $querynum=='' || $access_token=='' || $access_token_secret=='' || $oauth_session_handle) return array('0' => 'Forbidden');
if ($querynum == 1) {
$url = 'https://query.yahooapis.com/v1/yql';
// Show my profile
$params['q'] = 'select * from social.profile where guid=me';
} elseif ($querynum == 2) {
$url = 'https://query.yahooapis.com/v1/yql';
// here other query
}
$params['format'] = 'json'; //json xml
$params['Authorization'] = 'OAuth';
$params['oauth_session_handle'] = $oauth_session_handle;
$params['realm'] = 'yahooapis.com';
$params['callback'] = 'cbfunc';
$params['oauth_version'] = '1.0';
$params['oauth_nonce'] = mt_rand();
$params['oauth_timestamp'] = time();
$params['oauth_consumer_key'] = $consumer_key;
$params['oauth_callback'] = 'oob';
$params['oauth_token'] = $access_token;
$params['oauth_signature_method'] = 'HMAC-SHA1';
$params['oauth_signature'] = oauth_compute_hmac_sig($usePost? 'POST' : 'GET', $url, $params, $consumer_secret, $access_token_secret);
if ($passOAuthInHeader) {
$query_parameter_string = oauth_http_build_query($params, true);
$header = build_oauth_header($params, "yahooapis.com");
$headers[] = $header;
} else {
$query_parameter_string = oauth_http_build_query($params);
}
// POST or GET the request
if ($usePost) {
$request_url = $url;
logit("call_yql:INFO:request_url:$request_url");
logit("call_yql:INFO:post_body:$query_parameter_string");
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
$response = do_post($request_url, $query_parameter_string, 443, $headers);
} else {
$request_url = $url . ($query_parameter_string ? ('?' . $query_parameter_string) : '' );
logit("call_yql:INFO:request_url:$request_url");
$response = do_get($request_url, 443, $headers);
}
// extract successful response
if (! empty($response)) {
list($info, $header, $body) = $response;
if ($godebug==true) {
echo "<p>Debug: function call_yql info: <pre>" . print_r($info, TRUE) . "</pre></p>";
echo "<p>Debug: function call_yql header: <pre>" . print_r($header, TRUE) . "</pre></p>";
echo "<p>Debug: function call_yql body: <pre>" . print_r($body, TRUE) . "</pre></p>";
}
if ($body) {
$body = GetBetween($body, 'cbfunc(', ')');
$full_array_body = json_decode($body);
logit("call_yql:INFO:response:");
if ($godebug==true) echo "<p>Debug: function call_yql full_array_body: <pre>" . print_r($full_array_body, TRUE) . "</pre></p>";
}
}
// return object
return $full_array_body->query;
}
END code