I'm writing a project in Xamarin Forms, and today we try our app on Android device. And our request to googleAPI stop working. Here's code :
HttpWebRequest webRequest = WebRequest.Create(#"https://maps.googleapis.com/maps/api/place/search/json?location=" + position.Latitude + "," + position.Longitude + "&radius=1000&types=bar&sensor=false&key=APIKEY") as HttpWebRequest;
webRequest.Method = "GET";
webRequest.BeginGetResponse(new AsyncCallback(RequestCompleted), webRequest);
and then :
var request = (HttpWebRequest)result.AsyncState;
var response = (HttpWebResponse)request.EndGetResponse(result);
using (var stream = response.GetResponseStream())
{
var r = new StreamReader(stream);
var resp = r.ReadToEnd();
}
We got response and change it to json. On computer it works OK, but on Android it is saying INVALID REQUEST. Someone worked with Xamarin and know how to solve it?
If I would have to guess, I'd guess, that the locale/ language on your phone is different to that one on your pc.
HttpWebRequest webRequest = WebRequest.Create(#"https://maps.googleapis.com/maps/api/place/search/json?location=" + position.Latitude + "," + position.Longitude + "&radius=1000&types=bar&sensor=false&key=APIKEY") as HttpWebRequest;
There are implicit ToString() at ...n=" + position.Latitude + "," + position.Longitude + "&ra... that produce a localized output. But the google API needs the values with a . as decimal separator.
Append .ToString("G", CultureInfo.InvariantCulture)
HttpWebRequest webRequest = WebRequest.Create(#"https://maps.googleapis.com/maps/api/place/search/json?location=" +
position.Latitude.ToString("G", CultureInfo.InvariantCulture) +
"," + position.Longitude.ToString("G", CultureInfo.InvariantCulture) +
"&radius=1000&types=bar&sensor=false&key=APIKEY") as HttpWebRequest;
Related
Is there any possibility to upload a file on mobile browser (Safari on iOS, Chrome on Android)? Conventional methods doesn't seem to work. Maybe there are similar options to BrowserStack where file upload can actually work?
BrowserStack uses Appium to drive your Selenium tests on Android and iOS.
As given here, since Appium currently does not support uploads, BrowserStack too wouldn't be able to support File Upload on mobile devices.
This is a hacky file upload solution using base64 and JS, but it works, so hey, I hope you find this useful:
public CorePage UploadHack(string fileInputId, string contentType, string fileContent, string fileName, string angularScopeVar)
{
UploadFile(_filePath);
var uploadHack =
"(function(){" +
"function convert(base64){" +
"var raw = atob(base64);" +
"var arr = new Uint8Array(new ArrayBuffer(raw.length));" +
"for (var i = 0; i < raw.length; i++){" +
"arr[i] = raw.charCodeAt(i);" +
"}" +
"return arr; " +
"}" +
$"var file = new Blob([convert('{fileContent}')], {{'type':'{contentType}'}}); " +
$"file.name = '{fileName}'; " +
$"angular.element('#{fileInputId}').scope().{angularScopeVar} = file;" +
"})()";
Driver.ExecuteJavaScript(uploadHack);
return this;
}
Explanation of the issue: I have form with a signature pad on a mobile app, the user signs on it and submits the form. Then the sign should convert in to image and then upload in to folder server location.
I have used the following code to do that.
PHP Script
$img = str_replace('data:image/jpeg;base64,', '', $this->input->post('imgsource',TRUE));
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
file_put_contents($this->input->post('file_name',TRUE), $data);
JS Script
var img = document.createElement("img");
// added `width` , `height` properties to `img` attributes
img.width = "250px";
img.height = "250px";
img.src = "data:image/jpeg;base64," + base64_string;
var dt = new Date();
var timeupload = dt.getDate() + "" + (dt.getMonth()+1) + "" + dt.getFullYear() + "" + dt.getHours() + "" + dt.getMinutes() + "" + dt.getSeconds();
img.name = $("input[name='uid']").val()+"_"+currentTaskId+"_"+timeupload+'.jpeg';
AjaX Call to Service(written in Codeginter)
data: queryString+"&username="+localStorage.getItem('user')+"&password="+localStorage.getItem('password')+"&imgsource="+base64_string+"&file_name="+img.name+"&user_id="+$("input[name='uid']").val()+"&task_id="+currentTaskId,
here imgsource is the signature that I get from mobile app, decoding in to base64 to create an image and then pushing in to Server location.
the actual problem is the image get uploaded in to Server, when i try to download the image and see the image, its not readable/visible (ie, signature is not seen as an image)
Can anyone please suggest me in doing it.
You should url encode your base64 string before sending it to the server. Use
encodeURIComponent(base64_string) in your AJAX call.
I want to send files to the server using PhoneGap. here is my code below the following function parameter file to send. the problem that if I insert a fake url as localhost server it shows me server error code = 2, and if I insert a real url displays me file not found code = 1
function gotFile(file)
{
navigator.notification.alert(file.fullPath);
var options = new FileUploadOptions();
options.mimeType="image/jpg";
options.fileKey="file";
var params = {};
params.IdPrestation = "3d660013-3028-46c3-adfa-d7141a712ed7";
params.IdPhoto = "3a660013-3028-46c3-adfa-d7141a712ed7";
options.params = params;
options.chunkedMode = true ;
var ft = new FileTransfer();
ft.upload(file.fullPath,encodeURI('http://Myserver.fr/Phototheque.asmx/SavePhoto'),function(r)
{
//navigator.notification.alert(r.response,function(){});
alert(r.response,function(){});
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
},
function(e)
{
//navigator.notification.alert('Serveur Erreur:' + e.code,function(){});
cause_erreur(e.code);
/*
alert('Serveur Erreur:' + e.code,function(){});
alert("upload error source " + e.source);
alert("upload error target " + e.target)
*/
},
options
);//ft.upload
}
I do not exactly know your bug. However, your uploading code seems to be normal and the error may occur because of the file size or the network state.The same time, you can check in server whether request and response work as expected.
I am using Microsoft Sync Framework to sync the details from the Datadictionary on android device with SQL Server. Initially get success to sync all data from sql server. But after adding some data and when clicking on the Sync button getting the following error. Can you please tell me is anybody came across this?
[Sync Error]:Error occurs during sync. Please check logs below.
[Upload Change Response Error]: 500 Response: <ServiceError xmlns="http://schemas.datacontract.org/2004/07/Microsoft.Synchronization.Services" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><ErrorDescription>System.InvalidOperationException
serverBlob is empty
at Microsoft.Synchronization.Services.SqlProvider.SqlSyncProviderService.ApplyChanges(Byte[] serverBlob, List`1 entities)
at Microsoft.Synchronization.Services.UploadChangesRequestProcessor.ProcessRequest(Request incomingRequest)
at Microsoft.Synchronization.Services.SyncService`1.ProcessRequestForMessage(Stream messageBody)
</ErrorDescription></ServiceError>
In the below code, i'm getting xmlHttp.status=500 when clicking on the Sync button
this.sendRequest = function (serviceUri, successCallback, errorCallback, dir) {
TraceObj("[" + dir + " Request]:", serviceUri, this.dataObject());
// Construct HTTP POST request
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", serviceUri);
xmlHttp.setRequestHeader("Accept", "application/json");
xmlHttp.setRequestHeader("Content-Type", "application/json");
// Handle success & error response from server and then callback
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
var res = new SyncFormatter();
if (res.parse(xmlHttp.responseText)) {
TraceObj("[" + dir + " Response]:", serviceUri, res.dataObject());
alert("[" + dir + " Response]:", serviceUri, res.dataObject());
successCallback(res);
return;
}
}
TraceMsg("[" + dir + " Response Error]: ", xmlHttp.status + " Response: " + xmlHttp.responseText);
errorCallback(xmlHttp.responseText);
}
};
xmlHttp.send(this.toString());
};
}
I have found the root cause of the problem. That is when i get the values from datadictionary storage, value has the single quotes in the values so not able to load the values in webview. Now i have replaced single quotes by \'. Now working fine.
I'm triing to upload a file with phonegap to streamwork ( https://streamwork.com/api/Post_an_item_File_item.html ) .
I tried Phonegap's FileTransfer api which does not seem to send the request like streamwork wants it to:
var url =getItemsURL();
var item = "<?xml version='1.0' encoding='UTF-8'?>" +
"<item name='Test "+timestamp()+"'>" +
"<description>my upload</description>" +
"<file_item/>" +
"</item>";
var win = function(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
var fail = function(error) {
alert("An error has occurred: Code = "+ error.code);
}
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName="hello.txt";
options.mimeType="text/plain";
var params = new Object();
params.item = item;
options.params = params;
var paths = navigator.fileMgr.getRootPaths();
var ft = new FileTransfer();
ft.upload(paths[0] + "hello.txt",url, win, fail, options);
</code>
(actually I see that phonegap internally throws "java.io.FileNotFoundException: https://streamwork.com/v1/activities/..."
But the url should be correct since I then used the same in a manually written xhr.
function doUpload(data,fname,type,enc){
var url = getItemsURL();
var item = "<?xml version='1.0' encoding='UTF-8'?>" +
"<item name='My new activity item "+timestamp()+"'>" +
"<description>my upload</description>" +
"<file_item/>" +
"</item>";
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function(){
alert("xmlHttpObject.readyState = " + xhr.readyState + (xhr.readyState >= 3 ? " HTTP-Status = " + xhr.status : ''));
};
xhr.open("POST",url, true);
var boundary ="mime_boundary"
xhr.setRequestHeader("Accept", 'application/xml');
xhr.setRequestHeader("Content-Type", 'multipart/form-data; boundary=' + boundary);
var body = '--' + boundary + '\r\n';
body+='Content-Disposition: form-data; name="item"; filename="dummy.xml"\r\n';
body+= 'Content-Type: application/xml\r\n\r\n';
body+=item+'\r\n';
body+='--'+boundary+'\r\n\r\n';
body+='Content-Disposition: form-data; name="file"; filename="'+fname+'"\r\n';
body+='Content-Type: '+type+'\r\n';
body+='Content-Transfer-Encoding: '+enc+'\r\n\r\n';
body+=data+'--' + boundary + '--\r\n';
xhr.setRequestHeader('Content-length', body.length);
xhr.send(body);
}
which I call with
doUpload("lorem ipsum foo bar","test.txt","text/plain","binary");
this works in firefox when I give it the privilege to to cross domain stuff, but when I execute it on my android (htc desire hd) it does not work.
Firefox xhr readystate change outputs are: 1, 1, 2, 4(0)
Android xhr readystate change outputs are: 1, 4(0)
Does anyone has an idea, on what I am missing?
Thanks in advance
max