I developed an app in Windows phone 8/8.1, now I am trying to develop for android users. I am getting data from a website and displaying in my app. the website needs login userid,password. I successfully implemented it in C#. but I am unable to do it in java. can some guide me.
My code in C# :
HttpClientHandler handler = new HttpClientHandler();
HttpClient client = new HttpClient(handler, false);
handler.AllowAutoRedirect = true;
handler.PreAuthenticate = true;
Uri vceURI = new Uri("http://xxxx/default.aspx");
var html = await client.GetStringAsync(siteURI);
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
var viewstateNode = doc.GetElementbyId("__VIEWSTATE");
var eventvalidationNode = doc.GetElementbyId("__EVENTVALIDATION");
var viewstate = viewstateNode.GetAttributeValue("value", "");
var eventvalidation = eventvalidationNode.GetAttributeValue("value", "");
var formContent1 = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("__VIEWSTATE", viewstate),
new KeyValuePair<string, string>("__EVENTVALIDATION", eventvalidation),
new KeyValuePair<string,string>("txtLoginID",_username),
new KeyValuePair<string,string>("txtPWD",_pswd),
new KeyValuePair<string,string>("btnLogin","Go%21")
});
var outputDoc = await client.PostAsync("http://xxx/default.aspx", formContent1);
html = await outputDoc.Content.ReadAsStringAsync();
doc.LoadHtml(html);
// parsing(doc);
var studentInfoNode = doc.GetElementbyId("divStudInfo");
var _studentinfonode1 = studentInfoNode.ChildNodes;
var studentInfo = studentInfoNode.ChildNodes[0].ChildNodes;
the above studentInfo object contain required data
I tried using HttpClient + HttpPost but I am ending up in null exception :(
If some ever worked on similar application can you please help me.
Thanks
Related
I'm developing a video application with HLS streams.
These streams can only be played if I send in the request https custom headers.
On iOS I do like this:
NSMutableDictionary* headers = [NSMutableDictionary dictionary];
[headers setObject:#"MY_VALUE" forKey:#"MY_KEY"];
AVURLAsset* asset = [AVURLAsset URLAssetWithURL:videoTempURL options:#{#"AVURLAssetHTTPHeaderFieldsKey": headers}];
AVPlayerItem *myNewitem = [[AVPlayerItem alloc] initWithAsset:asset];
and on android like this:
DefaultHttpDataSource.Factory MGSource = new DefaultHttpDataSourceFactory(Util.getUserAgent( MainActivity.getContext(), "MY_USER_AGENT"), BANDWIDTH_METER);
MGSource.getDefaultRequestProperties().set("MY_KEY", "MY_VALUE");
and these methods work very well.
And I want to send these feeds on a ChromeCast.
So I look at how to do on Google Doc and they say this in receiver :
in this function :
sampleplayer.CastPlayer.prototype.loadVideo_ = function(info) {
this.log_('loadVideo_');
var self = this;
var protocolFunc = null;
var url = info.message.media.contentId;
...
host.updateSegmentRequestInfo = function(requestInfo) {
// example of setting CORS withCredentials
requestInfo.withCredentials = true;
// example of setting headers
//requestInfo.headers = {};
//requestInfo.headers['content-type'] = 'text/xml;charset=utf-8';
requestInfo.headers['MY_KEY'] = 'MY_VALUE';
console.log("################# SENDING HEADERS");
};
host.updateManifestRequestInfo = function(requestInfo) {
if (!requestInfo.url) {
requestInfo.url = this.url;
}
requestInfo.withCredentials = true;
};
host.updateLicenseRequestInfo = function(requestInfo) {
requestInfo.withCredentials = true;
};
But that does not work, can someone tell me how I can send custom headers in a URL to a ChromeCast.
Either in the Android sender or in the receiver.
thank you so much
I've created in Xamarin Forms for iOS a HttpClient function to send a picture from the device to my server. The core function is
var content = new MultipartFormDataContent();
var fileContent = new ByteArrayContent(fileBytes);
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = fName
};
fileContent.Headers.ContentDisposition.Parameters
.Add(new NameValueHeaderValue("userId", UserId.ToString()));
content.Add(fileContent);
using (var client = new HttpClient()) {
client.DefaultRequestHeaders.Add("authenticationToken", SyncData.Token);
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
// more code
}
}
I'm using System.Net.Http. I tried to use the same function for a project in Android but surprisingly it doesn't work. The problem is in the header: if I inspect fileContent I can see every keys but for webapi on the server FileName is not received.
After some logs, I changed this function adding more client.DefaultRequestHeaders like
client.DefaultRequestHeaders.Add("FileName", fName);
Now the webapi receives FileName param.
Now my question is: what did I wrong?
Personally, I use the Add method on MultipartFormDataContent that accepts a filename.
var content = new MultipartFormDataContent();
var fileContent = new ByteArrayContent(fileBytes);
...
// Use the overload Add method which accepts a file name
content.Add(fileContent, "FileName", fName);
...
I'm not sure if this will solve your problem or not, but it works for me.
I have two apps, one is a trial version the other the full version of a game, both made with adobe air. While saving data via the sharedobjects solution is no problem, I would like to use "one" savegame for both appsm, so users can keep their progress when upgrading to the full version. I tried around a little. But code like e.g. ...:
SharedObject.getLocal("myApp","/");
... doesnt work. So the question is, is there a way to have two Air apps using the same shared object? Or maybe if not using, at least "read" the shared object of another Air app?
Thanks in advance,
ANB_Seth
The answer is yes, I actually made a game transfer system for iOS and Android via network connection and 6 digit hash the user has to enter in the newly installed app to fetch the SO from the server. You could do this with a simple file stored locally on the SD card or other local storage device.
/**
* send this user's current save data to the server
*/
public function send():void{
var ba:ByteArray = new ByteArray();
// Main.sv.user - is the registerClassAlias object we write/read locally via SharedObject
ba.writeObject(Main.sv.user);
var name:String = Crypto.hash("Random Secrect Salt - typically user score, name, etc.");
// create 6 digit hash
var key:String = Crypto.hash(name).slice(0, 6).toUpperCase();
var request:URLRequest = new URLRequest ( 'https://sharedobject.com/transfer/save/name/'+name+'/key/'+key );
var loader: URLLoader = new URLLoader();
request.contentType = 'application/octet-stream';
request.method = URLRequestMethod.POST;
request.data = ba;
loader.addEventListener(IOErrorEvent.IO_ERROR, function (evt:Event) {
trace("error - network");
onSaveRestoreEvent(1);
});
loader.addEventListener(Event.COMPLETE, function (evt:Event) {
addChild(new BaseDialog("Save Sent To Server", "Your data has been sent to the server. To get this data back from the server " +
"you will need your secret key. Please write this six digit key down:\n"+name));
});
loader.load( request );
}
/**
* create a GET SO dialog
*/
public function receive():void{
var text:Sprite = new Sprite();
var textInput:TextInput = new TextInput();
textInput.width = Constants.SCREEN_WIDTH-100;
textInput.y = -50;
text.addChild(textInput);
var dialog:BaseDialog = new BaseDialog("Enter Secret Save Key", "Please enter your six digit secret save key in the field below, then press \"Get\".\n\n",
"Get", function():void{
text.removeChildren();
var url:String = "https://sharedobject.com/transfer/get/name/"+textInput.text; //servlet url
var request:URLRequest = new URLRequest(url);
//get rid of the cache issue:
var urlVariables:URLVariables = new URLVariables();
urlVariables.nocache = new Date().getTime();
request.data = urlVariables;
request.method = URLRequestMethod.GET;
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.BINARY;
loader.addEventListener(Event.COMPLETE, function (evt:Event) {
var loader:URLLoader = URLLoader(evt.target);
var bytes:ByteArray = loader.data as ByteArray;
bytes.position = 0;
if(bytes.length <= 10 || !(bytes.readObject() is User)){
onSaveRestoreEvent(2);
}else{
try{
bytes.position = 0;
Main.sv.user = (bytes.readObject() as User);
Main.sv.save();
onSaveRestoreEvent(0);
}
catch( e : EOFError ){
onSaveRestoreEvent(3);
}
}
});
loader.addEventListener(IOErrorEvent.IO_ERROR, function (evt:Event) {
trace("error - network");
onSaveRestoreEvent(1);
});
loader.load(request);
},
"Close", function():void{text.removeChildren();}, null, null, text);
dispatchEvent(new CreateBaseDialogEvent(dialog));
}
/**
* called after the restore save system is done
* #param prompt int [0 = complete][1 = error network][2 = error key][3 = error EOF]
*/
private function onSaveRestoreEvent(prompt:int):void{
var dialog:BaseDialog;
if(prompt == 0){
dialog = new BaseDialog("Restore Complete!", "All save data has been restored.");
}else if(prompt == 1){
dialog = new BaseDialog("Network Error!", "Please seek an internet connection and try again.");
}else if(prompt == 2){
dialog = new BaseDialog("Invalid Secret Key!", "The key you've entered seems to be invalid, or the save data has expired on the server. " +
"Data only lasts on the server for 24 hours.");
}else{
dialog = new BaseDialog("Error!", "There was an issue getting the file from the server. Please try the transfer again.");
}
dispatchEvent(new CreateBaseDialogEvent(dialog));
}
I need load images from a folder in application directory created in sd Card of mobile android
This is working in PC, but not in mobile version
Some solution ?
var imagesFin:File = File.applicationStorageDirectory.resolvePath("appImages/");
var files:Array = imagesFin.getDirectoryListing();
for (var i:uint = 0; i < files.length; i++){
var picLoader = new Loader();
picLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadPicture);
picLoader.load(new URLRequest(files[i].nativePath));
}
function loadPicture(event:Event):void {
var imgAtual = event.target.content;
ContainerImagesList.addChild(imgAtual);
}
This work for me:
var bytes:ByteArray = new ByteArray();
var myFileStream:FileStream = new FileStream();
var myFile:File = File.documentsDirectory.resolvePath(YOUR_PATH);
myFileStream.addEventListener(Event.COMPLETE, fileCompleteHandler)
myFileStream.openAsync(myFile, FileMode.READ);
function fileCompleteHandler(event:Event):void
{
myFileStream.readBytes(bytes);
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaded);
loader.loadBytes(bytes);
function imageLoaded(e:Event):void
{
addChild(Bitmap(loader.content));
myFileStream.removeEventListener(Event.COMPLETE, fileCompleteHandler);
myFileStream.close();
}
}
Cheers!
In iOS I never use resolvePath. I just use a relative url like "images/photo.jpg" and it works perfectly on any iOS device.
Instead of resolvePath you could also use URL schemes. It's a lot simpler "app:/images/photo.jpg" or "app-storage:/settings/prefs.xml".
http://help.adobe.com/en_US/as3/dev/WS5b3ccc516d4fbf351e63e3d118666ade46-7fe4.html
This is what I do to get all images in my image file cache
var imageFolder:File = new File("app:/img");
var getfiles:Array = imageFolder.getDirectoryListing();
I have created a native android app with PhoneGap + Sencha Touch 2. I have succeeded in uploading a file to the server, however, I am having a problem accessing a View from the upload success callback function in the FileTransfer upload() method. Here is my code:
upload callback:
uploadPicture: function(imageURI) {
var options = new FileUploadOptions(),
params = new Object(),
fileTransfer = new FileTransfer(),
builder = this.getBuilder(),
app = this.getApplication(),
uri = encodeURI('/myservlet');
options.fileKey = 'file';
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = 'image/jpeg';
params.myparams = something;
params.moreparams = evenmore;
options.params = params;
options.chunkedMode = false;
fileTransfer.upload(imageURI, uri, this.uploadSuccess.bind(this), this.uploadError.bind(this), options);
},
upload success function
uploadSuccess: function (r) {
var builderChild = this.getBuilderChild(),
data = r.response.attachment;
builderChild.addInstance(builderChild.config, data);
navigator.notification.alert('Attachment successful.');
}
When I get into the uploadSuccess function my builderChild object is undefined. I have been able to use the builderChild object through this same Controller in other functions, but not in uploadSuccess.
Any ideas?
Give this a try, this is how I used to do it.
var ftSuccess = Ext.bind(this.uploadSuccess, this),
ftError = Ext.bind(this.uploadError, this);
fileTransfer.upload(imageURI, uri, ftSuccess, ftError, options);
Hope this helped