Titanium appcelerator createHTTPClient() not working Android 5.0 Lollipop - android

I´m making a simple GET request in titanium and it seems to be that in versions of android 5.0 and up doesn´t work correctly. Here is the response of the console that im receiving.
< ANDROID 5.0
[INFO] : Status: 200, connectionType: GET
=> ANDROID 5.0
{"source":{"password":null,"status":0,"username":null,"autoRedirect":true,"bubbleParent":true,"allResponseHeaders":"","location":"","autoEncodeUrl":true,"apiName":"Ti.Network.HTTPClient","responseXML":null,"validatesSecureCertificate":false,"readyState":1,"domain":null,"responseText":"","responseData":null,"connectionType":"GET","statusText":null,"connected":false,"_events":{"disposehandle":{}}},"error":"Handshake
failed","code":-1,"success":false}
ERROR: "Handshake failed"
Here is the code that im using.
var url = "MY URL";
var loader = Titanium.Network.createHTTPClient();
loader.onload = function()
{
Titanium.API.info('Status: ' + this.status);
Titanium.API.info('ResponseText: ' + this.responseText);
Titanium.API.info('connectionType: ' + this.connectionType);
Titanium.API.info('location: ' + this.location);
};
loader.onerror = function (e) {
console.log(JSON.stringify(e));
console.log("ERROR: " + JSON.stringify(e.error));
};
loader.open("GET",url);
loader.send();
Hope you can help me with this.

This is an issue with the SSL certificate of the webserver.
You can verify that the certificate is valid from Chrome:

Related

Angular 4 : HTTPClient alway return an error 0

Hello i'm in trouble with angular HTTPclient.
I'm using Ionic 3 and Cordova so i cant use JQuery, that's why i use HTTPClient.
I have the following lines in my code :
var body = new URLSearchParams();
body.set('base64', this.getBase64Image(this.image));
body.set('x_poisson', "" + 0);
body.set('y_poisson', "" + 0);
body.set('x_gabarit', "" + this.points[this.points.length - 2]);
body.set('y_gabarit', "" + this.points[this.points.length - 1]);
body.set('largeur_image', "" + this.image.width);
body.set('hauteur_image', "" + this.image.height);
body.set('pseudo', pseudo);
var url = UrlServeur + "/index.php?module=Homologation&action=traiterPhotoApplication&listeCoin=" + corners;
console.log("[LOG][HOMO] Requesting on url: " + url);
this.http.post(url, body).subscribe(response => {
console.log("[LOG][HOMO] Homologation response: " + response);
loading.dismiss();
}, err => {
console.log(`[ERR][HOMO] Homologation error: (${err.status}) ${err.error}`);
loading.dismiss();
});
The probleme is that HTTPClient considere all response as error and i'm unable to get the body when i'm supposed to recieve a JSON.
Here are the log i have :
[17:09:59] console.log: [LOG][HOMO] Requesting on url:
http://X.XXX.XX.XXX/cdp/index.php?module=Homologation&action=traiterPhotoApplication&listeCoin=XXX,XXX,XXX,XXX,XXXX,XXX,XXXX,XXXX
[17:10:28] console.log: [ERR][HOMO] Homologation error: (0) undefined
When i watch on the logs of the serve X.XXX.XX.XXX it look like everything went well.
Thanks for reading, don't hesitate to ask for more informations.
Edit 1:
When i don't use an URLSearchParam the server don't get the post data event when manually setting post type to application/json manually
I tried with ResponseContentType as text :
var options = new RequestOptions();
options.responseType = ResponseContentType.Text;
this.http.post(url, body, options).subscribe(response => {
console.log(`[LOG][HOMO] Homologation response: ${response}`);
loading.dismiss();
}, err => {
console.log(`[ERR][HOMO] Homologation error: (${err.status}) [${err.error}] ${err}`);
loading.dismiss();
});
An i still get the following log : [ERR][HOMO] Homologation error: (0) [undefined] Response with status: 0 for URL: null
Edit 2:
It work when i build the app using ionic cordova build android --prod but not if i test using ionic cordova run android -lc
try send to post a simple obj (not a URLSearchParams)
var body:any = {
'base64':this.getBase64Image(this.image),
'x_poisson': "" + 0,
'y_poisson': "" + 0,
'x_gabarit': "" + this.points[this.points.length - 2],
'y_gabarit': "" + this.points[this.points.length - 1],
'largeur_image': "" + this.image.width,
'hauteur_image': "" + this.image.height,
'pseudo': pseudo
}
You also can try see if the response is "text" and not a json Object
this.http.post(url, body,{ responseType: 'text' })

Cordova 6.3.1 download PDF and open with FileSystem, FileTransfer and FileOpener2

Im banging my head against my desk because I dont seem to find any answer that works.
I want to download a PDF to the local storage of an android device, and then open it in an external reader as Android is not able to display PDF in the browser. For iOS I simply use the InAppBrowser plugin which works nice btw. Im using cordova 6.3.1.
So, this is my code:
if (cordova.platformId === "android") {
var remoteFile = url;
var localFileName = "tmp.pdf";
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
//var fileSystemRoot = cordova.file.dataDirectory; Does not work...
var fileSystemRoot = fileSystem.root.toURL()
console.log(cordova.file.dataDirectory);
var ft = new FileTransfer();
ft.download(remoteFile,
fileSystemRoot + "tmp.pdf", function(entry) {
cordova.plugins.fileOpener2.open(
entry.toURL(),
'application/pdf',
{
error : function(e) {
console.log('Error status: ' + e.status + ' - Error message: ' + e.message + ' - URL: ' + messageObj.url);
},
success : function () {
console.log('file opened successfully');
console.log(fileSystemRoot);
console.log(entry.toURL());
}
}
);
}, function(error) {
console.log("Error in downloading");
console.log(error);
});
}, function(error) {
console.log("Error in requesting filesystem");
console.log(error);
});
}
I have tried tons of different things. fileSystem.root.fullpath, fileSystem.root.toURL(), fileSystem.root.nativeURL but I always end up with a path that does not seem to correspond with the device. I always get the success message that the download worked, adobe reader pops up but says the file is not readable. Not a surprise to me as the path it gives me is something like:
file:///data/data/ch.novalogix.novalib/files/files
That can simply not be true? I searched the whole system for the uploaded file but I dont think its downloaded. I guess I always get a wrong path...
Any ideas?
Thanks in advance!
I used fixed paths instead of the localFileSystem.

Cordova fileTransfer works perfect on iOS, throws error code = 1 on Android

I'm developing a mobile app for iOS and Android using Cordova and Ionic Framework. There needs to be 'Send Photo' and related functionality, and I'm using Cordova's FileTransfer to do this.
It works perfectly on iOS simulator, but throws "error code = 1" on Android device.
I know this means file_not_found or similar.
Note it happens if I take a picture from camera, or choose one from gallery.
Here is my code:
$scope.takePic = function() {
var options = {
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: 0, // 0:Photo Library, 1=Camera, 2=Saved Photo Album
encodingType: 0 // 0=JPG 1=PNG
}
navigator.camera.getPicture(onSuccess, onFail, options);
}
var onSuccess = function(FILE_URI) {
window.resolveLocalFileSystemURL(FILE_URI, function(fileEntry) {
alert("full: " + JSON.stringify(fileEntry));
var realUrl = fileEntry.toURL();
$scope.picData = realUrl;
$scope.$apply();
console.log("real URL", realUrl);
});
};
var onFail = function(e) {
console.log("On fail " + e);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
Flash.success("Wysłano");
var response = JSON.parse(r.response);
$scope.attachment_id = response.data;
$scope.$apply();
$http.post($rootScope.baseServerUrl + 'Members/changeAvatar', {attachment_id: response.data}).success( function (response){
console.log(response);
});
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
$scope.send = function() {
Flash.warning('wysyłam');
var myImg = $scope.picData;
alert(myImg);
var options = new FileUploadOptions();
options.headers = {
Accept: "application/json",
Connection: "close"
}
options.fileKey="file";
options.fileName=$scope.picData.substr($scope.picData.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(myImg, encodeURI($rootScope.baseServerUrl + 'media/Attachments/add'), win, fail, options);
}
$scope.takePic and send are called by button clicks. There are a lot of alerts and console because I'm trying to find why its not working.
After picking a picture from the gallery on android I get:
file:///storage/sdcard0/download/file-name.jpg
on iOS simulator:
file:///Users//Library/Application%20Support/iPhone%20Simulator/7.1/Applications/B5FB2081-54E7-4335-8856-84C6499E6B07/tmp/cdv_photo_038.jpg
and by using this path I can show this picture by using <img src="{{picData}}"> this works on both platforms.
But if I try to send it on an Android device I get error Code = 1. On iOS sim it sends, photo, gets proper response, changes avatar...everything.
Both Cordova and plugins File and FileTransfer are up to date.
It looks like you might have a path error, file:///storage.sdcard0/download/file-name.jpg should be file:///storage/sdcard0/download/file-name.jpg if I'm not mistaken.
From perusing your code, it doesn't appear that you are parsing anything incorrectly. Maybe you want to try using an older more stable version of the file plugin if it is returning the wrong URI (and maybe file a bug report)? I haven't used the file plugin since they released 1.0, but from personal experience there have been bugs/regressions in the bleeding edge releases before.
You can target specific plugin versions from the cordova-cli using # like cordova plugin add org.apache.cordova.file#1.0.0
As well as specific tags/releases from github using # like cordova plugin add https://github.com/apache/cordova-plugin-file-transfer#r0.4.2
Maybe late but I've kinda fixed it.
In my view file I use:
<input id="file" name="file" type="file" onchange="angular.element(this).scope().addFile(this)" class="upload" accept="image/*" capture="camera"/>
so it fires $scope.addFile() from my controller as soon as you pick up file from galery:
$scope.addFile = function(item){
function uploadComplete(evt) {
/* This event is raised when the server send back a response */
$scope.imgId = JSON.parse(evt.target.responseText).data;
$scope.$apply();
$http.post($rootScope.baseServerUrl + 'Members/changeAvatar', {attachment_id: $scope.imgId}).success( function (response){
console.log(response);
$scope.User.attachment_id = $scope.imgId;
$scope.$apply();
});
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.")
};
var updateImage = function (element) {
$scope.$apply(function() {
$scope.theFile = element.files[0];
var formData = new FormData();
formData.append("file", $scope.theFile);
var xhr = new XMLHttpRequest()
xhr.addEventListener("load", uploadComplete, false)
xhr.addEventListener("error", uploadFailed, false)
xhr.open("POST", $scope.baseServerUrl + "media/Attachments/add")
xhr.setRequestHeader("Accept","application/json")
$scope.progressVisible = true
xhr.send(formData);
});
};
updateImage(item)
}
Works for all Android devices I tested, above 4.0 excluding 4.4 because of input type="file" bug, works on iOS simulator and devices with 8.1 system (should also on older but I didn't test it).
It's not a perfect solution, because you can use only pictures you already got on your phone. I couldnt figure it out how to use Cordova FileTransfer with our server authentication way: I was always getting "please log in" in response, even when I tried adding all needed headers, tokens, anything...
So even though this solution is far from what I wanted to achieve - it works. Hope it helps anyone.

How to integrate twitter, facebook social sharing api in Phonegap 2.7.0

I am trying to integrate twitter social sharing api to share links from my phone gap application.
as i have read from the blog given here
http://oodlestechnologies.com/blogs/Twitter-integration-on-PhoneGap-using-ChildBrowser-and-OAuth-for-iOS-and-Android-Platforms
Its is asking to install ChildBrowser plugin first.
I have downloaded the plugin from github as
https://github.com/alunny/ChildBrowser
And as i have tried to install it in my project the java file is giving too much errors.
As i have tried to resolve errors with suggestion given in eclipse. And when i run the project as android application it is saying exec() unknown plugin ChildBrowser
I am adding the plugin in config.xml as
<plugin name="ChildBrowser" value="android.com.phonegap.plugins.childBrowser.ChildBrowser"/>
I Just want to clear that the child browser plugin works with PhoneGap 2.7.0 Or not . If not then how can i use twitter sharing for my app.
If i am wrong anywhere please correct me. And also is there any best way to implement social sharing in phonegap application
Thanks
for PhoneGap social sharing, there is a much easier way. Just use the plugin mentioned here and you'll be able to share images via the native sharing widget, or directly to Twitter or Facebook.
Use simple InAppBrowser
Twitter Sharing url
var tweeter_url = 'https://twitter.com/intent/tweet?source=webclient&text='+your_text_or_share_url;
var ref = window.open(tweeter_url, 'random_string', 'location=no');
ref.addEventListener('loadstart', function(event) {
console.log(event.type + ' - ' + event.url);
} );
ref.addEventListener('loadstop', function(event) {
console.log(event.type + ' - ' + event.url);
if(event.url == 'https://mobile.twitter.com/'){
setTimeout(function() {
ref.close();
}, 1000);
}
} );
ref.addEventListener('exit', function(event) {
//console.log(event.type + ' - ' + event.url);
} );
Facebook Sharing url
var facebook_url = "https://www.facebook.com/dialog/feed?app_id=your_app_id&link="+encodeURIComponent(urlPost)+"&picture="+encodeURIComponent(urlPicture)+"&name="+encodeURIComponent(Title)+"&caption=&description="+encodeURIComponent(message)+"&redirect_uri="+your_redirect_uri;
var ref = window.open(url, 'random_string', 'location=no');
ref.addEventListener('loadstart', function(event) {
});
ref.addEventListener('loadstop', function(event) {
console.log(event.type + ' - ' + event.url);
var post_id = event.url.split("post_id=")[1];
var cancel_url = event.url.split("#")[0];
if(post_id != undefined){
setTimeout(function() {
ref.close();
}, 5000);
}
if(cancel_url != undefined && cancel_url == your_redirect_uri){
setTimeout(function() {
ref.close();
}, 1000);
}
});
ref.addEventListener('exit', function(event) {
});

Phonegap + Android status=0 returned from webservice

Phonegap Crew,
I have an problem with accessing a webservice using android. I have no problem accessing it using iOS.
The enclosed code uses a public webservice so you can try the code if you are so inclined.
On iOS we get a xmlhttp.status == 200 and returned data.
On Android we get a xmlhttp.status == 0.
We are using cordova-1.8.1.jar
We have the white list set in res/xml/cordova.xml
like this:
<access origin=".*"/>
I am bring that up because I am suspicious that our white list is not working.
here is the code:
function testweather(){
var xhr= new XMLHttpRequest();
xhr.onreadystatechange = function(){
alert(xhr.readyState);
if(xhr.readyState == 4){
if(xhr.status == 200){
$( "#result" ).append( xhr.responseText );
}
else{
alert("can't get response. a.status:"+xhr.status);
}
}
}
var url = "http://graphical.weather.gov/xml/SOAP_server/ndfdXMLserver.php";
xhr.open("POST", url,true);
xhr.setRequestHeader("SOAPAction", "http://graphical.weather.gov/xml/DWMLgen/wsdl/ndfdXML.wsdl#NDFDgenByDayLatLonList");
xhr.setRequestHeader("Content-Type", "text/xml;charset=UTF-8");
xhr.setRequestHeader("Content-Length", 1536);
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.setRequestHeader("Accept", "application/soap+xml, application/dime, multipart/related, text/*");
xhr.setRequestHeader("User-Agent", "IBM Web Services Explorer");
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("Pragma", "no-cache");
xhr.setRequestHeader("Connection", "close");
var soapEnv = '' +
'<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ndf="http://graphical.weather.gov/xml/DWMLgen/wsdl/ndfdXML.wsdl">' +
' <soapenv:Header/>' +
' <soapenv:Body>' +
' <ndf:NDFDgenByDayLatLonList soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' +
' <listLatLon xsi:type="dwml:listLatLonType" xmlns:dwml="http://graphical.weather.gov/xml/DWMLgen/schema/DWML.xsd">35.4,-97.6</listLatLon>' +
' <startDate xsi:type="xsd:date">2012-06-27</startDate>' +
' <numDays xsi:type="xsd:integer">3</numDays>' +
' <Unit xsi:type="dwml:unitType" xmlns:dwml="http://graphical.weather.gov/xml/DWMLgen/schema/DWML.xsd">e</Unit>' +
' <format xsi:type="dwml:formatType" xmlns:dwml="http://graphical.weather.gov/xml/DWMLgen/schema/DWML.xsd">24 hourly</format>' +
' </ndf:NDFDgenByDayLatLonList>' +
' </soapenv:Body>' +
'</soapenv:Envelope>';
xhr.send( soapEnv );
}
Sometimes when you do an AJAX request from the file protocol you will get a status of
0 but that is effectively a 200. Just change you if to be:
if(xhr.status == 200 || xhr.status == 0)
and you should be good to go.
Here is a blog post I wrote on using AJAX from PhoneGap.
http://simonmacdonald.blogspot.com/2011/12/on-third-day-of-phonegapping-getting.html
Updated: Apparently there is a bug in Android 2.x where setting the "Content-length" header causes the problem you describe. It looks like the bug has been fixed in Android 4.0.3. So try this code unmodified in the 4.0.3 emulator and it should work then come back to 2.x and remove the Content-length header to see if it works as well.
We gave up trying to run the webservice in Javascript and wrote a Java plugin to run the webservice. We needed it to work on a wide variety of devices and not rely on the user updating their device.
Try adding the below code in src > com.domain.appname > appname.java after
super.onCreate(savedInstanceState);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}

Categories

Resources