How do I specify data-binary in Titanium Appcelerator? - upload

I am trying to use the Dropbox API to upload a file. Here is the documentation from Dropbox:
curl -X POST https://content.dropboxapi.com/2/files/upload \
--header "Authorization: Bearer <get access token>" \
--header "Dropbox-API-Arg: {\"path\": \"/Homework/math/Matrices.txt\",\"mode\": \"add\",\"autorename\": true,\"mute\": false}" \
--header "Content-Type: application/octet-stream" \
--data-binary #local_file.txt
I have this in my Appcelerator project:
var xhr = Titanium.Network.createHTTPClient();
xhr.onload = function(e) {
//My function
};
xhr.open('POST','https://content.dropboxapi.com/2/files/upload');
xhr.setRequestHeader('Authorization', 'My Key');
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.setRequestHeader('Dropbox-API-Arg', '{"path":"/my_path/file.txt","mode":{".tag":"add"}}');
But I can't figure out how to send the data-binary argument. With my current code I can create a file in my Dropbox folder, but is just an empty file.

From http://docs.appcelerator.com/platform/latest/#!/api/Titanium.Network.HTTPClient, it looks like you just pass it into xhr.send(). You can pass a string, an object (which gets form-encoded), or a Titanium.Blob.
(Disclaimer: I've never used Appcelerator, so this is just what I surmise from reading the documentation.)

I figure out a way to do that. In my case I just need to upload a simple data structure, so I am using a JSON object:
var xhr = Titanium.Network.createHTTPClient();
xhr.onload = function(e) {
//My function
};
xhr.open('POST','https://content.dropboxapi.com/2/files/upload');
xhr.setRequestHeader('Authorization', 'My Key');
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.setRequestHeader('Dropbox-API-Arg', '{"path":"/my_path/file.txt","mode":{".tag":"add"}}');
var my_json = {
"item1" : "content1"
};
xhr.send(JSON.stringify(my_json));
I still can't send a BLOB (like a picture from the phone gallery), but it works if you pass the path of the file:
var my_path = Titanium.Filesystem.getFile(Titanium.Filesystem.tempDirectory,'my_folder');
var newFile = Titanium.Filesystem.getFile(my_path.nativePath,'file.txt');
newFile.createFile();
newFile.write('Content of my text file');
var params = {"data-binary" : newFile};
xhr.send(params);

Related

Deno oak server post body and reponse

I use oak server with Deno. But there is some problem with the response in post request.
My example:
const loginEp = async (ctx, next) => {//loginEp
if(!ctx.request.hasBody) {//if
ctx.throw(415);
}//if
const reqBody = await ctx.request.body({ type: 'json' }).value;
console.log(reqBody, typeof reqBody);
ctx.response.status = 200;
ctx.response.body = {key_one: "One"};
ctx.response.type = "json";
};//loginEp
const router = new Router()
router.post("/api/login", loginEp)
app.use(router.allowedMethods());
app.use(router.routes());
Try use:
curl --header "Content-Type: application/json" \
--request POST \
--data '{"login":"test","password":"test123"}' \
http://localhost:8010/api/login
The server receives the request and prints the body to the console. But I am not getting a response from the server.
If comment const reqBody = await ctx.request.body({ type: 'json' }).value; console.log(reqBody, typeof reqBody); then I get response.
I can't understand how to get the request body on the server and respond.
"value" on the body is also a promise, try awaiting it:
const reqBody = await (await ctx.request.body({ type: 'json' })).value;
If I try use:
const body = await ctx.request.body({ type: 'json' });
const reqBody = await body.value;
ctx.response.body = {key_one: "One"};
I receive error:
error: Uncaught (in promise) Error: The response is not writable.
throw new Error("The response is not writable.");

How to get all chats in website using zendesk chat api

There is any way to get all chats from zendesk to website.
I am using zendesk api for get all chats:
curl https://www.zopim.com/api/v2/chats \ -v -u {email_address}:{password}
Here Is my code :
public function getChat_messages(){
$sUrl = "https://www.zopim.com/api/v2/chats";
$authorization = "Authorization: Bearer a362fb582520105c720000631000d6f6f81111f0c95489b9673e722f5c59bf0";
$key= "-v -u email:password";
if (is_resource($rCh = curl_init($sUrl))) {
curl_setopt($rCh, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , 'Authorization: Bearer a362fb582520105c720000631000d6f6f81111f0c95489b9673e722f5c59bf0',
'-v -u email:password',
));
curl_setopt($rCh, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($rCh, CURLOPT_TIMEOUT, 3);
$arrResult = curl_exec($rCh);
$arrResult = explode("\n", $arrResult);
$response = curl_exec($rCh);
$err = curl_error($rCh);
curl_close($rCh);
}
print_r($response);
}
Help will be appreciated..
Thanks.. :)
You did well but there is a little mistake.
$sUrl = "https://www.{your_domain_name}.com/api/v2/chats";
You just copy and paste the line that is why you are getting error.
zopim is not your domain name use your domain name instead of zopim

Flutter- how to post https in this format?

I want to send post request in Dart.
curl looks like this.
curl -X POST "https://api-us.faceplusplus.com/facepp/v3/search" \
-F "api_key=<api_key>" \
-F "api_secret=<api_secret>" \
-F "face_token=c2fc0ad7c8da3af5a34b9c70ff764da0" \
-F "outer_id=facesetid"
I tried like this but error response says
MISSING_ARGUMENTS: api_key
final String apiKey = API_KEY;
final String apiSecret = API_SECRET;
final String faceToken = FACE_TOKEN;
final String outerId = OUTER_ID;
final data = jsonEncode({
'api_key': apiKey,
'api_secret': apiSecret,
'face_token': faceToken,
'outer_id': outerId
});
final http.Response request = await http.post(
'https://api-us.faceplusplus.com/facepp/v3/search',
body: data,
);
final String response = request.body;
final result = json.decode(response);
print(response);
print('------------------------');
print(result);
What am I missing?
How can I post this correctly?
From man curl
-F, --form <name=content>
(HTTP) This lets curl emulate a filled-in form in which a user has pressed the submit button. This causes curl to POST data using the Content-Type multipart/form-data
https://pub.dartlang.org/documentation/http/latest/http/MultipartRequest-class.html
var uri = Uri.parse("http://pub.dartlang.org/packages/create");
var request = new http.MultipartRequest("POST", url);
request.fields['user'] = 'nweiz#google.com';
request.files.add(new http.MultipartFile.fromFile(
'package',
new File('build/package.tar.gz'),
contentType: new MediaType('application', 'x-tar'));
request.send().then((response) {
if (response.statusCode == 200) print("Uploaded!");
});

Serialize and embed uploaded files to JSON

I have an API done with rails. I'm looking to upload multiple files in the same POST request. I would like to know if the only to do it by using form-data like mention here?
curl -X PATCH -H "Content-Type: multipart/form-data" -F "post[name]=wef" -F "post[catchphrase]=rteh reth erth erth" -F "post[posts_ids][]=8940" -F "post[screenshot1]=Ca9.png" -F "post[banner]=C34.png" -F "post[icon]=60eb.jpg" 'http://example.com:3000/api/v1/5282/posts/111605.json?api_key=2s4ctv21vudsgreeegrge'
Thanks
You can use base64 encoding.
On your client side:
HTML
<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image preview...">
Javascript
function previewFile() {
var preview = document.querySelector('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file);
} else {
preview.src = "";
}
}
Source: readAsDataURL documentation
If you don't use Javascript, make serializer for your platform. Data-URL is just data:[<MIME-type>][;charset=<encoding>][;base64],<data> (source)
On your server side:
Most likely you won't need to do anything at all, because paperclip/carrierwave will deserialize that stuff for you.

Meteor - Parse Data from Incoming HTTP Request

For outgoing HTTP requests (using meteor.http.call) I can define params and/or data. The results are then available (via results.content).
How do I access and parse the body/contents/data of incoming HTTP requests?
Using iron-router, I have got as far as this:
Router.map(function () {
this.route('httpTest', {
path: '/httpTest',
action: function () {
var request = this.request;
var response = this.response;
console.log('request_body: '+ request.body);
// request.body does not work. what should it be????
N.B. I understand that I CAN access query parameters, but I want to access form data and/or json data from the body of an incoming http request.
The request is an incoming http message, which is a Readable Stream, so you can get the data of the request by reading from that stream.
The following should work (but I haven't tested it):
var readable = this.request;
var alldata = "";
readable.on('data', function(chunk) {
alldata += chunk;
})
readable.on('end', function() {
console.log('do something with alldata');
});
It may not be working because of the missing where: 'server'. Here is a working example:
Router.map(function() {
this.route('test', {
where: 'server',
action: function() {
console.log(this.request.body.make);
console.log(this.request.body.model);
this.response.writeHead(200, {'Content-Type': 'text/html'});
this.response.end('hello!\n');
}
});
});
From the command line I can hit this route with:
curl -X POST -H "Content-Type: application/json" -d '{"make":"honda","model":"civic"}' http://localhost:3000/test
Which prints the expected honda and civic in the server's terminal. It looks like this.request.body is already parsed so you can access any variables directly which is nice if your input is json.
To read the raw body, without having Node.js JSON-ify it, in a synchronous way, I used this:
Router.route("my/api", function() {
var rawBody = "";
var chunk;
while ((chunk = this.request.read()) !== null) {
rawBody += chunk;
}
}, { where: "server" });
(the asynch way proposed in another answer here didn't worked for me, although it should as per Node.js documentation).

Resources