Skip to content

Instantly share code, notes, and snippets.

@Priyansh-Kedia
Created Sep 3, 2021
Embed
What would you like to do?
Link preview in Android
if (!url.contains("http")) {
url = "http://$url"
}
openGraphResult = OpenGraphResult()
try {
val response = Jsoup.connect(url)
.ignoreContentType(true)
.userAgent(AGENT)
.referrer(REFERRER)
.timeout(TIMEOUT)
.followRedirects(true)
.execute()
val doc = response.parse()
val ogTags = doc.select(DOC_SELECT_QUERY)
when {
ogTags.size > 0 ->
ogTags.forEachIndexed { index, _ ->
val tag = ogTags[index]
val text = tag.attr(PROPERTY)
when (text) {
OG_IMAGE -> {
openGraphResult!!.image = (tag.attr(OPEN_GRAPH_KEY))
}
OG_DESCRIPTION -> {
openGraphResult!!.description = (tag.attr(OPEN_GRAPH_KEY))
}
OG_URL -> {
openGraphResult!!.url = (tag.attr(OPEN_GRAPH_KEY))
}
OG_TITLE -> {
openGraphResult!!.title = (tag.attr(OPEN_GRAPH_KEY))
}
OG_SITE_NAME -> {
openGraphResult!!.siteName = (tag.attr(OPEN_GRAPH_KEY))
}
OG_TYPE -> {
openGraphResult!!.type = (tag.attr(OPEN_GRAPH_KEY))
}
}
}
}
} catch (e: Exception) {
e.printStackTrace()
launch(Dispatchers.Main) {
listener.onError(e.localizedMessage)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment