-
-
Save hasankucuk/8fb52e60bb0c8c71ce320aa8e2d68448 to your computer and use it in GitHub Desktop.
Android Kotlin - Extract og tags from website using jsoup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class JsoupOgTagParser(var urlToParse: String) : AsyncTask<Void, Void, Void?>() { | |
private var title: String? = null | |
private var desc: String? = null | |
private var image: String? = null | |
private var url: String? = null | |
private var listener: Listener? = null | |
override fun doInBackground(vararg voids: Void): Void? { | |
val con = Jsoup.connect(urlToParse) | |
val doc = con.userAgent("Mozilla").get() | |
val ogTags = doc.select("meta[property^=og:]") | |
when { | |
ogTags.size > 0 -> | |
ogTags.forEachIndexed { index, element -> | |
val tag = ogTags[index] | |
val text = tag.attr("property") | |
when (text) { | |
"og:image" -> image = tag.attr("content") | |
"og:description" -> desc = tag.attr("content") | |
"og:url" -> url = tag.attr("content") | |
"og:title" -> title = tag.attr("content") | |
} | |
} | |
} | |
return null | |
} | |
override fun onPostExecute(void: Void?) { | |
super.onPostExecute(void) | |
if (listener != null) { | |
listener!!.onSuccess(title, url, desc, image) | |
} | |
} | |
fun setListener(listener: Listener) { | |
this.listener = listener | |
} | |
internal interface Listener { | |
fun onSuccess(title: String?, url: String?, desc: String?, image: String?) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Flowable.fromCallable { | |
val doc = Jsoup.connect(linkArray[0]).userAgent("Mozilla").get() | |
val ogTags = doc.select("meta[property^=og:]") | |
when { | |
ogTags.size > 0 -> | |
ogTags.forEachIndexed { index, element -> | |
val tag = ogTags[index] | |
val text = tag.attr("property") | |
when (text) { | |
"og:image" -> imagePreview = tag.attr("content") | |
"og:description" -> descPreview = tag.attr("content") | |
"og:url" -> urlPreview = tag.attr("content") | |
"og:title" -> titlePreview = tag.attr("content") | |
} | |
} | |
} | |
}.subscribeOn(Schedulers.io()) | |
.observeOn(AndroidSchedulers.mainThread()) | |
.subscribe({ | |
setLinkPreviewOnScreen() | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment