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();
}
Related
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)\/(.+)
I have a shorten url done by http://goo.gl/
I need to get the original url. Is there any api to do that in ANDROID.
What I tried for make shorter -
compile 'com.andreabaccega:googlshortenerlib:1.0.0'
GoogleShortenerPerformer shortener = new GoogleShortenerPerformer(new OkHttpClient());
String longUrl = "http://www.andreabaccega.com/";
GooglShortenerResult result = shortener.shortenUrl(
new GooglShortenerRequestBuilder()
.buildRequest(longUrl)
);
if ( Status.SUCCESS.equals(result.getStatus()) ) {
// all ok result.getShortenedUrl() contains the shortened url!
} else if ( Status.IO_EXCEPTION.equals(result.getStatus()) ) {
// connectivity error. result.getException() returns the thrown exception while performing
// the request to google servers!
} else {
// Status.RESPONSE_ERROR
// this happens if google replies with an unexpected response or if there are some other issues processing
// the result.
// result.getException() contains a GooglShortenerException containing a message that can help resolve the issue!
}
Load the ShortURL with a HttpURLConnection, then you can read out the target URL with
httpURLConnection.getHeaderField("location");
Full solution
URL url = new URL("http://goo.gl/6s8SSy");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
Log.v("Full URL", httpURLConnection.getHeaderField("location"));
Can't test live right now, but this should be working.
I made my solution. What I did -
I open a webview without visibility then call that url.Then on page load complete I a fetching the url
WebView webView;
webView = (WebView)findViewById(R.id.help_webview);
webview.loadUrl("http://goo.gl/tDn72f");
webView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
String myResult = webView.getUrl();
}
});
I wanna save all web page including .css .js on android by programmatically.
So far I tried html get method and jsoup , webview content but all of them I could not save all page with css and js. These methods just save html parts of WEB Page. When I save the all page ,I want to open it offline.
Thanks in advance
You have to take the html, parse it and get the urls of the resources and then make requests for those urls too.
public class Stack {
private static final String USER_AGENT = "";
private static final String INITIAL_URL = "";
public static void main(String args[]) throws Exception {
Document doc = Jsoup
.connect(INITIAL_URL)
.userAgent(USER_AGENT)
.get();
Elements scripts = doc.getElementsByTag("script");
Elements css = doc.getElementsByTag("link");
for(Element s : scripts) {
String url = s.absUrl("src");
if(!url.isEmpty()) {
System.out.println(url);
Document docScript = Jsoup
.connect(url)
.userAgent(USER_AGENT)
.ignoreContentType(true)
.get();
System.out.println(docScript);
System.out.println("--------------------------------------------");
}
}
for(Element c : css) {
String url = c.absUrl("href");
String rel = c.attr("rel") == null ? "" : c.attr("rel");
if(!url.isEmpty() && rel.equals("stylesheet")) {
System.out.println(url);
Document docScript = Jsoup
.connect(url)
.userAgent(USER_AGENT)
.ignoreContentType(true)
.get();
System.out.println(docScript);
System.out.println("--------------------------------------------");
}
}
}
}
I have similar problem...
Using this code we can get images,.css,.js. However some html contents are still missing.
For instance when we save a web page via chrome,there are 2 options.
Complete html
html only
Out of .css,.js,.php..."Complete html" consists of more elements than "only html". The requirement is to download the html as complete like chrome does in the first option.
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 ;)
I am validating a URL before to open using Patterns.WEB_URL. It works perfect until lollipop that return true to "http://www.google" url for example.
final String registrationUrl = "http://www.google";
final Pattern urlPattern = Patterns.WEB_URL;
Boolean bool = urlPattern.matcher(registrationUrl).matches();
Any idea how to validate a URL? URLUtil.isValidUrl() dont work for me.