Blog Infos
Author
Published
Topics
,
Published

With the development of messaging applications, starting from WhatsApp for Chat Groups, to Slack for workspaces, link sharing is a crucial part.

WhatsApp provides a preview for the link that you enter in the input box, which helps users gain information about the content, without opening the link, increasing the user experience.

In this blog, we will see how we can create a preview like WhatsApp in Android.

The Open Graph protocol enables any web page to become a rich object in a social graph. While many different technologies and schemas exist and could be combined together, there isn’t a single technology which provides enough information to richly represent any web page within the social graph. The Open Graph protocol builds on these existing technologies and gives developers one thing to implement.

For building the code for link preview, we will be using the Open Graph Protocol.

We will start with creating the data class for the response from the link.

data class OpenGraphResult(
    var title: String? = null,
    var description: String? = null,
    var url: String? = null,
    var image: String? = null,
    var siteName: String? = null,
    var type: String? = null
)

In this data class, we add title, description, url, image, siteName, and type, all of this can be fetched using OGP. You can read more about the different fields here.

Now let us see how we can actually get some information from the link.

Let us start by adding some dependencies for Jsoup and Kotlin Coroutines.

implementation 'org.jsoup:jsoup:1.10.3'     
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9'

Jsoup is an open-source Java library designed to parse, extract, and manipulate data stored in HTML documents.

Now we start the code.

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)
}
}
view raw OgParser.kt hosted with ❤ by GitHub

Job Offers

Job Offers


    Developer (m/w/d) Backend/ Mobile

    Payback GmbH
    Cologne, Germany
    • Full Time
    apply now

    Lead Android Engineer

    ASOS
    London
    • Full Time
    apply now

    Senior Android Engineer – Big Release Team

    Zalando SE
    Berlin
    • Full Time
    apply now
Load more listings

OUR VIDEO RECOMMENDATION

Behind the Curtains

All smartphones have cameras, and we know we can use specific APIs to get amazing shots. But are they the best cameras? Probably not! What if we wanted to drive an external camera, much more powerful than a smartphone? How would we connect to it, and how would we trigger a shot? This and much more…
READ MORE

Jobs

We first check if the link contains, http or not, so as to make the link consistent.

Next, we connect to the url using Jsoup. Let us see what individual functions are meant for.

ignoreContentType :- True if you wish to ignore the type of content from the url. Unrecognised content might throw IOException.
userAgent :- Sets the request user-agent header
referrer :- Sets the request referrer header
timeout :- Sets the request timeout. IOException is thrown is timeout occurs
followRedirects :- True if you want the link to follow server redirects

Next, we parse the response and save it in a variable. We then select the CSS Query from this parsed data using doc.select(DOC_SELECT_QUERY).

We then iterate over the tags that we get and extract individual properties as per our requirements.

That is all you need to do to extract information from a link. This information can be shown to the user in any way possible.

You can find the variables used with Jsoup here.

private val AGENT = "Mozilla"
private val REFERRER = "http://www.google.com"
private val TIMEOUT = 10000
private val DOC_SELECT_QUERY = "meta[property^=og:]"
private val OPEN_GRAPH_KEY = "content"
private val PROPERTY = "property"
private val OG_IMAGE = "og:image"
private val OG_DESCRIPTION = "og:description"
private val OG_URL = "og:url"
private val OG_TITLE = "og:title"
private val OG_SITE_NAME = "og:site_name"
private val OG_TYPE = "og:type"
view raw VARNAMES.kt hosted with ❤ by GitHub

In this blog, we read about how one can implement OGP in android, to fetch information from the link.

You can also check out a small library I made for the same task. This library simplifies the task and gives the link information with just one line of code.

YOU MAY BE INTERESTED IN

YOU MAY BE INTERESTED IN

blog
Nowadays authentication has become common in almost all apps. And many of us know…
READ MORE
blog
Collections are a set of interfaces and classes that implement highly optimised data structures.…
READ MORE
blog
Hi, today I come to you with a quick tip on how to update…
READ MORE
blog

How to animate BottomSheet content using Jetpack Compose

Early this year I started a new pet project for listening to random radio…
READ MORE

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu