Jsoup: How to get Video url? - android

I am trying to parse video url from html. I am using Jsoup parse to parse it. I want to parse
<meta property="og:video" content="http://video.foxnews.com/assets/video-player.swf?video_id=2475698001001&d=video.foxnews.com&auto_play=true">
from this html. How can i get this content from the above line.
Now my code is:
try {
Connection.Response response = Jsoup
.connect(htmlUrl)
.userAgent(
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.21 (KHTML, like Gecko) Chrome/19.0.1042.0 Safari/535.21")
.timeout(10000).execute();
int statusCode = response.statusCode();
Log.d("TAG", " status code is: " + statusCode);
if (statusCode == 200) {
doc = Jsoup.connect(htmlUrl).timeout(1000 * 100).get();
Log.d("TAG","Document is created : " + doc );
Elements element = doc.select("meta");
for (Element urls : element) {
//System.out.println(urls.text());
Log.d("TAG", " url is: " + urls.attr("property") + " " + urls.attr("og:video"));
}
} else {
System.out.println("received error code : " + statusCode);
}
What should change in my code?
Thank you in advance!

Assuming you are using asynctask/thread for network related operation.
Assuming its the first meta you can do as below
String myhtml ="<meta property="+"og:video" +" "+"content="+"http://video.foxnews.com/assets/video-player.swf?video_id=2475698001001&d=video.foxnews.com&auto_play=true"+">";
Document doc = Jsoup.parse(myhtml);
Element eMETA = doc.select("meta").first();
String s = eMETA.attr("content");

I changed my code as follows:
try {
Connection.Response response = Jsoup
.connect(htmlUrl)
.userAgent(
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.21 (KHTML, like Gecko) Chrome/19.0.1042.0 Safari/535.21")
.timeout(1000000).execute();
int statusCode = response.statusCode();
Log.d("TAG", " status code is: " + statusCode);
if (statusCode == 200) {
doc = Jsoup.connect(htmlUrl).timeout(1000 * 1000).get();
Elements meta = doc.select("meta[property=og:video]");
for (Element src : meta) {
if (src.tagName().equals("meta"))
Log.d("TAG", " content: " + src.attr("content"));
else
Log.d("TAG", src.tagName());
}
} else {
System.out.println("received error code : " + statusCode);
}
} catch (IOException e) {
Log.d("TAG", " Exception " + e);
e.printStackTrace();
}

Related

Titanium Android : Facebook dialog image URL not properly formatted

I developing an Android application using Titanium Appcelerator. I had tried to Post text and Image via facebook feed dialog
.. But error while load my local image URL..
var fileimg = Titanium.Filesystem.getFile(backupDir.nativePath, "myimg.jpg");
var fb_data1 = {
description : "Some good text",
picture : fileimg.nativePath,
link : "www.googlee.com",
};
facebook_qfav.dialog("feed", fb_data1, showRequestResult);
function showRequestResult(e) {
var s = '';
if (e.success) {
s = "SUCCESS";
if (e.result) {
s += "; " + e.result;
}
if (e.data) {
s += "; " + e.data;
}
if (!e.result && !e.data) {
s = '"success",but no data from FB.I am guessing you cancelled the dialog.';
}
} else if (e.cancelled) {
s = "CANCELLED";
} else {
s = "FAILED ";
if (e.error) {
s += "; " + e.error;
alert("facebook Share " + s);
}
}
}
ERROR: "Image URL not properly formatted"
File path will be like this: file:///storage/sdcard0/myimg.jpg
But if i pass the remote URL to the picture property , the image is shown in the dialog...
what happens to the local URL..?
I think the only issue is that nativepath has capital P in it. so, its : nativePath
so instead of picture : fileimg.nativepath, It Should be picture : fileimg.nativePath,
Documentation.
Hope it helps.

Gear SDK SAFileTransfer FILE_IO error

I'm trying to send file from Android host to Samsung Gear device using Samsung Mobile SDK no matter how had I try, always get FILE_IO error.
I was trying all available permissions (on both sides).
Could anyone send me any hint?
Android side:
String filename = "file:///storage/emulated/0/Download/TestRecipe2-25.zip";
if (mGuruAgentService != null) mGuruAgentService.sendFile(filename);
public int sendFile(String fileName) {
if (mFileTransfer == null)
registerForFileTransfer();
if (mFileTransfer != null) {
try {
Log.i(TAG, "Sending file " + fileName);
tx = mFileTransfer.send(mPeerAgent, fileName);
return tx;
} catch (Exception e)
{
Log.i(TAG, "Cannot send file" + e.getMessage());
}
}
return 0;
}
Tizen side:
function fileReceiveInt() {
var newFilePath = "downloads/file.zip";
var receivefilecallback =
{
onreceive: function(transferId, fileName)
{
console.log("Incoming file transfer request form the remote peer agent. transferId: " + transferId + " file name : " + fileName);
try {
gFileTransfer.receiveFile(transferId, newFilePath);
} catch(e) {
console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
}
},
onprogress: function(transferId, progress)
{
console.log("onprogress transferId: " + transferId + ", progress : " + progress);
},
oncomplete: function(transferId, localPath)
{
console.log("File transfer complete. transferId: " + transferId);
},
onerror: function(errorCode, transferId)
{
console.log("FileReceiveError transferId: " + transferId + " code : " + errorCode);
}
}
try {
console.log('setting recieve interface');
gFileTransfer = SAAgent.getSAFileTransfer();
gFileTransfer.setFileReceiveListener(receivefilecallback);
} catch (err) {
console.log('getSAFileTransfer exception <' + err.name + '> : ' + err.message);
}
}
I will always get onError in tizen with FILE_IO error :(
I was testing gFileTransfer.receiveFile(transferId, ""); for default path, and File:///opt/usr/media/Downloads...
My tizen privileges:
<tizen:privilege name="http://tizen.org/privilege/content.read"/>
<tizen:privilege name="http://developer.samsung.com/privilege/accessoryprotocol"/>
<tizen:privilege name="http://tizen.org/privilege/content.write"/>
<tizen:privilege name="http://tizen.org/privilege/filesystem.read"/>
<tizen:privilege name="http://tizen.org/privilege/filesystem.write"/>
<tizen:privilege name="http://tizen.org/privilege/unlimitedstorage"/>
Thanks in advance for any help.
Change both filepaths and it should work.
Change Android's side to:
String filename = Environment.getExternalStorageDirectory() + "/Download/TestRecipe2-25.zip";
Change Tizen's side to:
var newFilePath = "file:///opt/usr/media/Downloads/file.zip";

Receiving HTTP Bad Request when calling a .NET Webservice using SOAP only from Android

EDIT: For anyone using the same method as I am (building a Soap.java file and using sockets), stop! Use the kSoap-Android library as it automates pretty much everything and has little to no bugs like this.
I'm creating an android application where you can quicly check your timeroster for the classes in the next week. To do this, I use 2 servers:
The server that hosts the timerosters for every student in HTML form
(I do not manage this server)
The server that hosts my webservice (which I manage). It's a .NET webservice and is finished.
The android device connects to the Webservice-server and sends the function "login" with parameters "username": "usernameX" and "password": "passwordX".
The webservice-server then retrieves the login-page from the timeroster-server with the "username" and "password" fields as post parameters. The timeroster-server will respond with a html-page, that will be parsed by the webservice-server and depending on it's contents, the webservice will respond to the Android device with either "Success" or "AuthenticationFail".
To do this, I use the SOAP-architecture on my Android Device, which sends a SOAP-enveloppe to the webservice. The webservice then creates HttpWebRequest- and HttpWebResponse-objects that retrieve the html-source from the timeroster-server.
This approach has worked for me so far using the Socket-class and I have been able to login to the timeroster-server, using my android device. However, the problem lies with another function.
My webservice supports 2 functions: "login" and "GetList". I can perfectly call the "login"-function from my android and receive a "Success"-string. But when I call the "GetList"-function (that takes 3 parameters: a username, a password and a listType), it returns a 400 Bad Request.
When I send the exact same http-request to the webservice-server with Fiddler, I don't receive a 400 Bad Request error.
Why am I getting a 400 error ONLY when I use my android-device? Is there any way I can fix this?
Images for visualisation:
Login-function (using Android):
Login-function (using Fiddler):
GetList-function (using Android) - ERROR HERE:
GetList-function (using Fiddler):
Code used in Android to send data to socket:
public String sendRequest()
{
String s = "";
Socket socket = null;
try
{
socket = new Socket(Server, Port);
}
catch(Exception ex)
{
return "UnknownClientError";
}
String stringbuffer = "";
try
{
socket.getOutputStream();
boolean flag = true;
PrintWriterSuper printwriter = new PrintWriterSuper(socket.getOutputStream());
Scanner scanner = new Scanner(socket.getInputStream());
int i = 295 + MethodName.length() * 2 + XmlNamespace.length();
for(int j = 0; j < ParamNames.size(); j++)
{
String s1 = (String)ParamNames.elementAt(j);
String s2 = (String)ParamData.elementAt(j);
i += s1.length();
i += s2.length();
}
printwriter.println("POST " + WebServicePath + " HTTP/1.1");
printwriter.println("Host: " + Server);
printwriter.println("Content-Type: text/xml; charset=utf-8");
printwriter.println("Content-Length: " + String.valueOf(i));
if(!SoapAction.equals(""))
printwriter.println("SOAPAction: \"" + SoapAction + "\"");
printwriter.println("Connection: Close");
printwriter.println();
printwriter.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
printwriter.println("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">");
printwriter.println("<soap:Body>");
printwriter.println("<" + MethodName + " xmlns=\"" + XmlNamespace + "\">");
for(int k = 0; k < ParamNames.size(); k++)
{
String s3 = (String)ParamNames.elementAt(k);
String s5 = (String)ParamData.elementAt(k);
printwriter.println("<" + s3 + ">" + s5 + "</" + s3 + ">");
}
printwriter.println("</" + MethodName + ">");
printwriter.println("</soap:Body>");
printwriter.println("</soap:Envelope>");
printwriter.println();
boolean flag1 = false;
int byte0 = 10;
long l = System.currentTimeMillis();
String s4;
while(scanner.hasNextLine() && !flag1)
{
s4 = scanner.nextLine();
stringbuffer += s4 + "\n";
if(System.currentTimeMillis() - l > (long)(1000 * byte0))
flag1 = true;
}
scanner.close();
if(!flag1)
{
String requestString = printwriter.toString();
String s6 = MethodName + "Result";
int i1 = stringbuffer.toString().indexOf("<" + s6 + ">") + s6.length() + 2;
int j1 = stringbuffer.toString().indexOf("</" + s6 + ">");
s = stringbuffer.substring(i1, j1);
} else
{
s = "Error: timed out by client";
}
try{
socket.close();
}catch(Exception ex){}
}
catch (Exception e) {
s = e.getMessage() + "\n" + e.getStackTrace().toString();
}
return s;
}

How android can parse mailto url containing Japanese or Chinese characters

i've tried to parse a mailto url which contains Japanese or Chinese characters by using MailTo.parse(url) but it return null.
it's ok with English characters. How do I resolve that?
There's my code and logcat:
try {
url = URLDecoder.decode(url,"UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d(TAG, "url: " + url);
MailTo mt = MailTo.parse(url);
Log.d(TAG, "body: " + mt.getBody());
Log.d(TAG, "subject: " + mt.getSubject());
07-12 12:50:34.861: D/Fbaku(9484): url: mailto:?subject=幕末の時代を生き抜け!&body=iPhoneとiPod Touch対応の風雲幕末史を一緒にやりませんか?
07-12 12:50:34.861: D/Fbaku(9484): subject: null
07-12 12:50:34.861: D/Fbaku(9484): body: null
Edit: sorry, my mailto url contains a link in body like this: https://stackoverflow.com/posts/17607307
So MailTo.parse(url).getBody() and MailTo.parse(url).getSubject() return NULL
How can i fix it?
try by using toString() method
so change
Log.d(TAG, "body: " + mt.getBody());
Log.d(TAG, "subject: " + mt.getSubject());
to
Log.d(TAG, "body: " + mt.getBody().toString());
Log.d(TAG, "subject: " + mt.getSubject().toString());

FB.api('/me') always giving error code:2500 in phonegap android

I am using facebook plugin to login and logout a user, which are working fine. The problem is when I request for the logged in user details using the function FB.api('/me'), it always gives the following error:
{"message":"An active access token must be used to query information about the current user.","type":"OAuthException","code":2500}
I used the debug mode to check PluginResult(pr) and JSONObject of the response. JSONObject contains the user information, which I required, I dont get where I am doing wrong.
Plz help......
MY CODE:
function login() {
FB.login(function(response) {
if (response.session) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + JSON.stringify(response) + '.');
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
},{scope: 'email,user_likes'});
}
function logout() {
FB.logout(function(response) {
console.log(localStorage.getItem("user_fb_log_status"));
localStorage.setItem("user_fb_log_status","LOGGED_OUT");
alert('logged out');
});
}
The above code is working fine to login and logout the user. Below is the code i used to get the user details,
function me() {
FB.api('/me', { fields: 'id, name, picture' }, function(response) {
if (response.error) {
alert(JSON.stringify(response.error));
} else {
var data = document.getElementById('data');
fdata=response.data;
console.log("fdata: "+fdata);
response.data.forEach(function(item) {
var d = document.createElement('div');
d.innerHTML = "<img src="+item.picture+"/>"+item.name;
data.appendChild(d);
});
}
});
}
You need access token to retrieve more details than basic user information. Check that whether you have correct access token in Debug Tool to and ensure that you have all require permissions set permission.
Problem solved after changing the "session" in 'getResponse' method in ConnectPlugin to "authResponse"
FB.api method is working fine for me to get the user details and post a feed to the facebook after I change the following method in ConnectPlugin.java as following.
public JSONObject getResponse() {
String response = "{" + "\"status\": \""
+ (facebook.isSessionValid() ? "connected" : "unknown") + "\","
+
// "\"session\": {" + "\"access_token\": \""
// + facebook.getAccessToken() + "\"," + "\"expires\": \""
// + facebook.getAccessExpires() + "\","
// + "\"session_key\": true," + "\"sig\": \"...\","
// + "\"uid\": \"" + this.userId + "\"" +
"\"authResponse\": {" +
"\"accessToken\": \"" + facebook.getAccessToken() + "\"," +
"\"expiresIn\": \"" + facebook.getAccessExpires() + "\"," +
"\"session_key\": true," +
"\"sig\": \"...\"," +
"\"userId\": \"" + this.userId + "\"" +
"}" + "}";
try {
return new JSONObject(response);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new JSONObject();
}

Categories

Resources