How to check whether the youtube url has username or channel? - android

i want to check the youtube url is username or channelid ?
for example https://www.youtube.com/user/aaaaaaaa
https://www.youtube.com/channel/UC--------hdch . how to check?

You can check if the url contains the string user for User and channel for Channel.
String url = "https://www.youtube.com/user/aaaaaaaa"
if(url.contains("/channel/")){
//url is a channel url
}else if(url.contains("/user/")){
//url is a user url
}

Well the problem is that you have to verify that there is a link to user or a channel directly after the youtube address,
val url: String = "https://www.youtube.com/user/aaaaaaaa"
if(url.contains("/channel/")){
//url is a channel url
}else if(url.contains("/user/")){
//url is a user url
}
Here I didn't used to check if the string contains youtube.com/user/ because some urls may have youtu.be/user/ which is valid and offical address, so just checking that there is forward slash before and after the identifier it makes sure that it'll work as expected!
EDIT1:
OP wants a regex solution so:
val regex = Regex("""(?:youtube\.com|youtu\.be)\/(user|channel)""")
val result = regex.find("https://www.youtube.com/user/aaaaaaaa")
when(result!!.groupValues[1]){
"user" -> //code
"channel" -> //code
else -> {} //or replace {} with code
}
EDIT2:
You could use this expression to get the information about the url
val regex = Regex("""(?:https:\/\/)*(?:www\.)*(youtube\.com|youtu\.be)\/(user|channel)\/(\w+)""")
val result = regex.find("https://www.youtube.com/user/aaaaaaaa")!!
when(result.groupValues[2]){
"user" -> //code
"channel" -> //code
else -> {} //or replace {} with code
}
println(result.groupValues[0]) //https://www.youtube.com/user/aaaaaaaa
println(result.groupValues[1]) //youtube.com
println(result.groupValues[2]) //user
println(result.groupValues[3]) //aaaaaaaa
EDIT3:
As OP suggested this does not work for a symbol (non word literal) hence, instead of /w+ you could use .+
So the finalized regex would be
(?:https:\/\/)*(?:www\.)*(youtube\.com|youtu\.be)\/(user|channel)\/(.+)

Related

Retrofit request url prevent urlencode android

I have a retrofit request
#GET("{link}")
suspend fun getFilePart(#Path(value = "link") link: String): Deferred<NetworkResponse<ResponseBody, NetworkError>>
and when i call it i pass a 'link'
val base = if (BuildConfig.DEBUG) BuildConfig.TRANSFER_URL_DEBUG else BuildConfig.TRANSFER_URL
apiManager.appApiService(base).getFilePart(it.link)
Lets say the link is something like "https://storage_dev.example.com/10002/6d197e1e57e37070760c4ae28bf1..." but in the Logcat i see that some characters get urlEncoded.
For example
the following Url
https://storage_dev.example.com/10002/6d197e1e57e37070760c4ae28bf18d813abd35a372b6a1f462e4cef21e505860.1&Somethingelse
turns to
https://storage_dev.example.com/10002/6d197e1e57e37070760c4ae28bf18d813abd35a372b6a1f462e4cef21e505860.1%3FSomethingelse
As i can see the link is a String that has many characters inside that get encoded like "&" has turned to "%3F"
How can i prevent this?
You can add encoded = true to your request param to tell retrofit to not encode it again:
/**
* Specifies whether the parameter {#linkplain #value() name} and value are already URL encoded.
*/
boolean encoded() default false;
Example:
#Path(value = "link", encoded = true)
If your link includes the baseurl part you should use #Url to avoid that problem
#GET
suspend fun getFilePart(#Url link: String): Deferred<NetworkResponse<ResponseBody, NetworkError>>
I think I'm late but however this is how I solved it ..
my issue was the url to containes " so on request url it gets encoded then looks like this domain.com/api/%22SOME_URL_%22
simply just add interceptor to catch the request and decode it.
if(it.request().url().toString().contains("api/MY_SUB_DOMAIN")){
val newUrl = java.net.URLDecoder.decode( it.request().url().toString(),
StandardCharsets.UTF_8.name()) // <--- This is your main solution (decode)
.replace("\"", "") // <---- I had to do this to remove parenthasis "
requestBuilder.url(newUrl) // <--- DONT FORGET TO ASSAIGN THE NEW URL
}

Android Uri building ignore parameters except if at least one parameter is present

I have a strange behaviour when I click on a link in a webview that is a PDF file link.
For example: https://my.server.com/foobar.pdf
So I have made some research and this link will start a dowload in my webview.
I have a DownloadListener and a onDownloadStart method.
In it I send the URL to Android so that PDF apps on phone can open it.
My strange behaviour is here. If the link in the webview does not have parameters I am not able to add parameters in the URL but if the URL have one parameter -> my parameters are added.
Example will be more meaningful.
Here url in link is "https://my.server.com/foobar.pdf"
val uriTest = Uri.parse(url).buildUpon()
.appendQueryParameter("key1", val1)
.appendQueryParameter("key2", val2)
.build()
val intent = Intent(Intent.ACTION_VIEW, uriTest)
startActivity(intent)
So when the PDF app called by startActivity(intent) call the URL on my server I have no parameters in URL and on my server I see a call to "https://my.server.com/foobar.pdf" not to "https://my.server.com/foobar.pdf?key1=val1&key2=val2".
BUT
If the url in link is "https://my.server.com/foobar.pdf?t=t" when my Android code is executed on my server side I can see a call to ""https://my.server.com/foobar.pdf?t=t&key1=val1&key2=val2". My parameters are added in this case.
Is it normal? Am I missing something?
Thanks for your help!
---EDIT---
I also tried to add my parameters in the string directly and it is the same -> my parameters are ignored until the URL I get has one parameter.
Example: I get "https://my.server.com/foobar.pdf" and I do:
val url1 = url + "?key1=" + val1
or
val url1 = "$url?key1=$val1"
val yourUrl = StringBuilder("https://my.server.com/foobar.pdf")
val parameters = hashMapOf<String, String>()
parameters["key1"] = "val1"
parameters["key2"] = "val2"
var count = 0
for (i in parameters.entries) {
if (count == 0)
yourUrl.append("?${i.key}=${i.value}&")
else
yourUrl.append("${i.key}=${i.value}&")
count++
}
val yourNewUrl = yourUrl.substring(0, yourUrl.length - 1)
Timber.e("URL: $yourNewUrl")
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(yourNewUrl))
startActivity(intent)
Happy coding :)

[Android ]How to get redirected url on Android app

in android app, I want to get redirected URL
in my app, I want to play HLS(.m3u8) file
before access to HLS's URL we access other URL to redirect.
I coded as below but it doesn't work
val conn = url.openConnection() as HttpURLConnection
conn.instanceFollowRedirects
conn.connect()
val inputStream :InputStream = con.inputStream
mediaPlayer.setDataSource(con.url.path)
inputStream.close()
I tried direct url to .m3u8 and it works as below
mediaPlayer.setDataSource(con.url.path)
Check your HTTP Response. If the status code is between 300 and 399 it means that the page is being redirected to another page. To determine the destination read the "Location" header field:
object RedirectHelper {
fun getRedirectUrl(connection: HttpURLConnection): String? {
val code = connection.responseCode
return if (code in 300..399) {
connection.getHeaderField("Location")
} else null
}
}

How to add a protocol to a URL if it does not exist? (in an Android app)

I am working on an app that gets a URL link from the user via edit text widget. How can I check if a given URL has a protocol? And if it doesn't, how can I add the correct protocol for the specific URL?
For example if the user entered: google.com
how can I make it become: https://google.com
The main problem is knowing the correct URL protocol for a given address (is it http/https/ftp? and so on).
You can use String.startsWith() to check if the url String starts with http:// or not
public String valid_url(final String url)
{
if (!url.startsWith("http://") && !url.startsWith("https://"))
{
return "http://" + url;
}
return url;
}
first check if url has protocol using .contains() method
and get protocol using .indexof() and .substring() method
string url = editText.getText().toString();
string protocol;
if(url.contains("://")){
//url has a protocol
int index = url.indexof("://");
//get protocol
protocol = url.substring(0,index-1);
}else{
//url does not have a protocal
// add your protocol to begining of the url
}
You can use android web kit URLUTIL class
package android.webkit;
URLUtil.guessUrl("your web address/String")
example scenarios:
www.testurl.com
testurl.com
testurl
result:
http://www.testurl.com/
Just compare the your output string with .contains() property
String value = editText.getText().toString();
if(!value.contains("https://")) {
// add https:// to ur string
}else {
// No need to add
}
This solution worked for me:
if(!url.startsWith("www.")&& !url.startsWith("http://") && !url.startsWith("https://")){
url = "www."+url;
}
if(!url.startsWith("http://") && !url.startsWith("https://")){
url = "http://"+url;
}
Hope this will help you.
As already adviced use the URL class of the SDK.
Here an example:
var urlWithScheme = new URL("https://www.google.com");
var urlWithoutScheme = new URL("www.google.com");
if (urlWithScheme.getProtocol() != null && urlWithScheme.getProtocol().length() > 0) {
System.out.println("Given URL includes scheme: " + urlWithScheme.getProtocol());
}
if (urlWithoutScheme.getProtocol() != null && urlWithoutScheme.getProtocol().length() > 0) {
System.out.println("Given URL includes scheme: " + urlWithoutScheme.getProtocol());
} else {
System.out.println("Url has no Protocol and you can't guess it by the domain name, because under this name all possible services can exist!");
}
If the given URL has not protocoll you can't guess it. Because under a domain name there can exist any protocol specific service in parrallel.
I would narrow it down to only support http and https. For this you could write a test like connect to https url, if success use it, because https is prefered. If you get redirect or not connection try http ;)

Validate Specfic URL input in EditText for android

My application is about downloading an image from a specific website e.g. www.example.com/img-...
The user will input the url for the img to the EditText field. e.g. www.example.com/img-123
My problem is that when the user inputs a wrong URL, i.e. one with no no image, it is empty e.g. www.example.com/img-222
I want to detect this and tell the user their input does not link to an image and try again.
I'm using the isValidUrl() function to detect if the input is a WEB_URL only but what I want is that when the entered url has no image, the program should tell them it is an incorrect format for url.
I'm using Jsoup.connect(url).get(); to connect to the url and get the image and save it
private boolean isValidUrl(String url) {
Pattern p = Patterns.WEB_URL;
Matcher m = p.matcher(url);
if(m.matches())
return true;
else
return false;
}
We can use android native android.webkit.URLUtil class to validate any kind of url.
URLUtil.isValidUrl(downloadImaheEditText.getText().toString());
it will return true if valid else false.
String[] schemes = {"http","https"}; //DEFAULT schemes = "http", "https", "ftp"
UrlValidator urlValidator = new UrlValidator(schemes);
if (urlValidator.isValid("http://www.google.com")) {
//url is valid
}else{
//url is invalid
}
Use Apache commons-validator URLValidator class
I tried this and it worked for me. Please find the code snippet below:
public static boolean isURL(String url) {
Pattern p = Patterns.WEB_URL;
Matcher m = p.matcher(url.toLowerCase());
return m.matches();
}

Categories

Resources