i am trying to do login application which takes id and password..when i click on logi button then it will connect to our local server by JSON..with the specified URL..the code is..
var loginReq = Titanium.Network.createHTTPClient();
loginReq.onload = function()
{
var json = this.responseText; alert(json);
var response = JSON.parse(json);
if (response.data.status == "success")
{ alert("Welcome ");
}
else
{ alert(response.data.status);
}
};
loginReq.onerror = function(event)
{
alert(event.toSource());
//alert("Network error");
};
loginBtn.addEventListener('click',function(e)
{ if (username.value != '' && password.value != '')
{
var url = 'our local url action=login&id='+username.value+'&pwd='+password.value;
loginReq.open("POST",url);
loginReq.send();
}
else
{
alert("Username/Password are required");
}
});
Here it is not connecting our URl..so it is entering into loginReq.onerror function...instead of loginReq.onload function..why it is throwing run time error.. The same code working fine with Iphone..
The Run Time Error is..
TypeError:Cannot call property toSource in object{'source':[Ti.Network.HttpClient],specified url} is not a function,it is a object.
This is wat the error..please let me Know...
Apparently the toSource() function does not exist in android, as it is an object. Try debugging and see what the object event contains.
You could do that by adding a line above the alert line, and adding a debug line to it.
Look in debug mode and see all variables
"toSource()" is not a documented function for either platform, and I also do not see it in the source for Titanium Mobile. If you aren't getting the error on iOS, I'm guessing it is because the error handler isn't getting called. Perhaps your emulator or device does not have internet access, whereas your iOS simulator or device does?
Regardless, error handling in the HTTPClient normally looks something like this:
loginReq.onerror = function(e)
{
Ti.API.info("ERROR " + e.error);
alert(e.error);
};
Related
we have an app under xamarin android build with visual studio 2017.
this app works since three years without any problems.
since two weeks and I don't know why actually some device can't sync with our back end.
It's really strange because nothing has change in this part .
this error does not appear on all devices but on one or two from time to time
we use the dll httpClient for to sync the datas with our backend.
If i put a break point inside the postAsync I have an exception with this -> Cannot access a disposed object. Object name: 'System.Net.Sockets.NetworkStream
Any one has an idea about how to solve this ? also what does it meam ?
Here is it the code of the postAsync method :
thanks for our time and comment guys
public override HttpResult ExecutePost(Uri target, string body)
{
var client = new HttpClient();
client.MaxResponseContentBufferSize = MaxHttpResponseBufferSize;
try
{
var requestContent = new StringContent(body, RequestContentEncoding, RequestContentType);
var response = client.PostAsync(target, requestContent).Result;
if (response.IsSuccessStatusCode)
{
var content = response.Content.ReadAsStringAsync().Result;
return new HttpResult(content, null, null);
}
return new HttpResult(null, "Response is empty", response.StatusCode.ToString());
}
catch (Exception e)
{
return new HttpResult(null, "Problem with the HttpPost", e.Message);
}
}
I experienced the same issue. Have been battling for 6 hours on this issue.
If you read the error, I was getting (Failed to connect to localhost/127.0.0.1:7113). If you put localhost in your browser or swagger tool it will work but if you put https://127.0.0.1:7113/api/weatherforecast in your browser it will not work. It will give you a certificate problem.
So I think you have to resolve 127.0.0.1 to localhost with https certificate on your local dev machine.
I'm building a MAUI app with Visual Studio 2022 Preview.
So I solved this issue by deploying my API to AZURE.
Then update to the azure url for example:
string apiUrl = "https://weatherforecast.azurewebsites.net/api/weatherforecast";
and then it worked brilliantly. Like super brilliantly.
Here is my code:
public void LoginAsync()
{
HttpClient client = new HttpClient();
string apiUrl = "https://weatherforecast.azurewebsites.net/api/weatherforecast";
UserCredentials.EmailAddress = LoginUIEntity.EmailAddress;
UserCredentials.Password = LoginUIEntity.Password;
string serialized = JsonConvert.SerializeObject(UserCredentials);
var inputMessage = new HttpRequestMessage
{
Content = new StringContent(serialized, Encoding.UTF8, "application/json")
};
inputMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
var message = client.PostAsync(apiUrl, inputMessage.Content).Result;
if (message.IsSuccessStatusCode)
{
var apiResponse = message.Content.ReadAsStringAsync();
UserCredentials = JsonConvert.DeserializeObject<UserCredentials>(apiResponse.Result);
if (UserCredentials.IsValid)
{
UserCredentials.IsLoggedIn = true;
}
else
{
ErrorMessage = "Invalid credentials supplied.";
}
}
}
catch (Exception ex)
{
ErrorMessage = "An error has occurred. Please contact support if the error persists.";
}
}
}
thanks for the link your provide.
I've try up the buffer on the postasync / try to sync in wifi OR 3G / delete special character in json / ...
but nothing work
we have move the prod database to the test and try to sync the data to the test database with postman. with postman the result was ENTITY TOO LARGE !
Json is size > 1.2 mega and the default value inside IIS is set to 1 mega
Here is it the problem ...
thanks problem solve
I've got an Android app I'm building with Unity that logs info on a simple python http server (hosted on a Digital Ocean Droplet). Here's my coroutine for poking the server:
IEnumerator pokeServer()
{
Debug.Log( "Establishing Server Connectivity..." );
using( var www = UnityWebRequest.Get( ServerURL ) )
{
Debug.Log( "Send Web Request" );
ServerStatus = ConnectionStatuses.AttemptingToConnect;
yield return www.SendWebRequest();
if( www.isNetworkError || www.isHttpError )
{
if( www.isNetworkError )
{
Debug.Log( "NETWORK ERROR: " + www );
}
else
{
Debug.Log( "HTTP ERROR: " + www );
}
ServerStatus = ConnectionStatuses.Unavailable;
}
else
{
Debug.Log( "Success! Server available!" );
ServerStatus = ConnectionStatuses.Connected;
}
}
}
If I run this on the Unity Editor, everything works fine. I can get a response from my server without issue. If I build and run this on an Android, the request is not sent to my server and I get no error message. The last line in the above code that's run is "yield return www.SendWebRequest();"
I've looked at the logcat, and there's no error. My server never gets any requests. However, if I poke "https://www.google.com," I do indeed get a response. This leads me to believe that this is some sort of http vs https issue, but I have no idea where to start. This code has been working for me for a very long time. Any advice would be very welcome!
I'd been using this phone from University of Pennsylvania's wireless network. It turns out that I can make an http request from a desktop but I can't do it from a phone. I took one of the devices home and tried it from my personal wifi and it all worked fine.
I recently started writing a detail automated test script on MonkeyTalk for my application. I am fascinated with the power of this tool, but there is a small issue i am facing.
I am writing a data driven test case using csv file which is running file. But now I want to induct some verification on view, I believe that could be done using javascript but I couldn't be able to work it around. Can anyone show me how.
Here is what i am doing :
1) my script file to run the data driven test case for csv file
Script DataDrivenLogin.mt RunWith login.csv
2) my other script file where i am using the views
load("libs/MyApp.js");
MyApp.DataDrivenLogin.prototype.run = function(email, _password) {
/**
* #type MT.Application
*/
var app = this.app;
email = (email != undefined && email != "*" ? email : "<email>");
_password = (_password != undefined && _password != "*" ? _password : "<_password>");
app.image("email").tap();
app.input("Email Address").tap({timeout:"2000"});
app.input("Email Address").enterText(email, {timeout:"2000"});
app.input("Password").tap({timeout:"2000"});
app.input("Password").enterText(_password, {timeout:"2000"});
app.button("login").tap({timeout:"2000"});
try {
app.image("Open").verify(); //if label exists
} catch(Exception) {
app.debug().print("Label not found");
}
app.image("Open").tap({timeout:"2000"});
app.table("left_drawer").selectIndex("8", {timeout:"2000"});
app.button("Yes").tap({timeout:"2000"});
app.image("Open").tap({timeout:"2000"});
};
but it is not working my script is still breaking what I want to do is that if the view doesn't exists the script won't break and start from top again for next data value.
Help is much appreciated. Thanks!!!
As far as i understood the problem here, if label does not exist then this
app.image("Open").tap({timeout:"2000"});
will also break. Try to put this as well in try block.
As
........
app.input("Password").enterText(_password, {timeout:"2000"});
app.button("login").tap({timeout:"2000"});
try {
app.image("Open").verify(); //if label exists
app.image("Open").tap({timeout:"2000"});
} catch(Exception) {
app.debug().print("Label not found");
}
app.table("left_drawer").selectIndex("8", {timeout:"2000"});
app.button("Yes").tap({timeout:"2000"});
app.image("Open").tap({timeout:"2000"});
I've been trying to run the following code but the callbacks [ok() and ko()] are not called.
Using Worklight 6.2 (Cordova 3.4).
function wlCommonInit() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
success, fail);
window.resolveLocalFileSystemURL(cordova.file.applicationDirectory
+ "www/index.html", ok, ko);
}
function ko(e) {
alert("NO");
}
function ok(fileEntry) {
alert("OK");
}
On the other hand requestFileSystem callbacks are called regularly.
The code snippet in the question will not work in Android due to a Cordova defect: https://issues.apache.org/jira/browse/CB-7273.
To progress further, it would help to understand what are your plans for the file itself.
Do you simply want the path to the file
Or do you want to alter the contents of the file?
Or?
You can read more about file system operations in Cordova in this question/answer: Where does LocalFileSystem.PERSISTENT point to?
I managed to access local fiiles in Worklight running an Android environment using a XMLHttpRequest:
//Works only on Android
function prendiCaricaRisorsaWorklight(percorsoPiuNomeFile) {
var xmlhttp = new XMLHttpRequest();
var risposta = "";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4
&& (xmlhttp.status == 200 || xmlhttp.status == 0)) {
risposta = xmlhttp.responseText;
alert(risposta);
}
}
xmlhttp.open("GET", "file:///android_asset/www/default/"
+ percorsoPiuNomeFile, true);
xmlhttp.send(null);
}
Usage example:
prendiCaricaRisorsaWorklight("css/cssInterno.css");
prendiCaricaRisorsaWorklight("js/jsInterno.js");
This shows on Android an alert with the file content.
I am developing android application using titanium and in my application I need to upload image from gallery to remote server location.I already tried this
button1.addEventListener('click',function(e)
{
Titanium.Media.openPhotoGallery({
success : function(event)
{
var update_pic = Titanium.Network.createHTTPClient();
update_pic.onerror = function()
{
Titanium.API.info('error');
alert(JSON.parse(this.responseText).error);
}
update_pic.onload = function()
{
actInd.hide();
}
update_pic.open('POST','server-address/profile/update.json');
update_pic.send(
{
"user[avatar]":event.media,
"authenticity_token":"sD5hjlI=",
"user[name]":'nilesh',
"commit":"Update Profile"
});
}
})
})
But its not working for me. Process stop at point user[avatar]:event.media,.Is this the proper way to send image to remote server. I also tried this
update_pic.send({
user_avatar : event.media,
authenticity_token : "sD5hjlI=",
user_name : 'nilesh',
commit : "Update Profile"
})
when I send parameter like this, it not sending my http request and When I remove user_avatar : event.media It sending my request mean there is problem with user_avatar.Any solution....Need help. Thank you..........
try adding this line below "var update_pic = ..."
update_.setRequestHeader("ContentType", "image/jpeg");
taken from: http://developer.appcelerator.com/question/9481/how-to-upload-images-with-filename-to-the-server