Understands that using Patterns.WEB_URL.matcher(url).matches() will able to validate if that string is a valid url, however it will required in a full format which contain https: / .com.
In my case, i want to validate if the json return a string in correct format for path e.g /images/slider/my/myImage.jpg; which does not contain https or any. How can i do this?
What i want to do is something like:
if(ImageUrl equal "/images/slider/my/myImage.jpg" FORMAT) {
//Do something here
} else //ImageUrl = myImage.jpg {
//Add "/images/slider/my/" infront of the text
}
P.s: My image link will be like www.abc.com/images/slider/my/myImage.jpg
Use URLUtil to validate the URL as below.
URLUtil.isValidUrl(url)
It will return True if URL is valid and false if URL is invalid.
Another way is given below.
public static boolean checkURL(CharSequence input) {
if (TextUtils.isEmpty(input)) {
return false;
}
Pattern URL_PATTERN = Patterns.WEB_URL;
boolean isURL = URL_PATTERN.matcher(input).matches();
if (!isURL) {
String urlString = input + "";
if (URLUtil.isNetworkUrl(urlString)) {
try {
new URL(urlString);
isURL = true;
} catch (Exception e) {
}
}
}
return isURL;
}
This link will explain how you can check the url is available or not.
For more about URLS please visit this
Please have a try
Related
I am working on a web Browser, I have a SearchView in it, for user to input queries. I want to differentiate between a search query or a web address. My current code just add http://www. in front of any query that comes in and try to load it.
This is my current code.
String query = search_q;
if(!query.startsWith("www.")&& !query.startsWith("http://")){
query = "www."+ query ;
}
if(!query.startsWith("http://")){
query = "http://"+query;
}
if( Patterns.WEB_URL.matcher(query).matches()){ //checks if the query looks like an URL
web1.loadUrl(query);
}
else
web1.loadUrl("https://www.google.com//search?q=+"+search_q);
The problem is that Patterns.WEB_URL.matcher(query).matches() returns true even if http://www.abc is passed into it.
check
if( Patterns.WEB_URL.matcher(query).matches() && isUrl(query)){ //checks if the query looks like an URL
web1.loadUrl(query);
}
function defintion isUrl:-
public Boolean isUrl(String query){
int a=0;
int onlyfind=0;
for (int i = 0 ; i<query.length() ; i++){
if (query.charAt(i) == '.')
a++;
if(a==1){
onlyfind= i;
}
}
if(a==1){
if(query.substring(0,onlyfind+1).equals("http://www"))
return false;
}
return true;
}
Try validating the url(query) using this method:
//isValidURL(query);
boolean isValidURL(String url) {
try {
new URI(url).parseServerAuthority();
return true;
} catch (URISyntaxException e) {
return false;
}
}
If it returns false, then:
web1.loadUrl("https://www.google.com//search?q=+"+search_q);
I think the best way to validate URL is using regex. Because if you are working on a browser, you should not limit the validation of string queries that starts with www, what if the website is dev.website.com? it is a valid website URL, or what if the address starts with https and not just http?. So I think Try using regex to have a reference pattern in validating if the query string is URL or not:
private boolean isURL(CharSequence searchQuery) {
Pattern urlPattern = Pattern.compile("(https?:\\/\\/(?:www\\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\\.[^\\s]{2,}|www\\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\\.[^\\w\\D\\S]{2,}|[^\\s]{2,}[a-zA-Z0-9]\\.[^\\s]{2,})");
Matcher matcher = urlPattern.matcher(searchQuery);
return matcher.matches();
}
Then call that method:
String query = search_q;
if(isURL(query)) {
web1.loadUrl(query);
} else {
web1.loadUrl("https://www.google.com//search?q=+"+search_q);
}
Hope this helps.
i can't access the inner tag to get the image "url"
here my tag name is "enclosure" and it contain another one called "url" and this is what i want to get...
here the a whole class i created
**public class ParseApplications {
private static final String TAG = "ParseApplications";
private ArrayList<NewsFeeds> application;
public ParseApplications() {
this.application = new ArrayList<>();
}
public ArrayList<NewsFeeds> getApplication() {
return application;
}
public boolean Parse(String xmlData) {
boolean status = true;
NewsFeeds currentNews = null;
boolean InEntry = false;
String textValue = "";
boolean gotImage = false;
try {
// XmlPullParserFactory This class is used to create implementations of XML Pull Parser defined in XMPULL
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
//coming line mean that the xml parse i will handle it by my code
/*
Specifies that the parser produced by this factory will provide support for XML namespaces.
By default the value of this is set to false.
Parameters
awareness
boolean: true if the parser produced by this code will provide support for XML namespaces; false otherwise.
*/
factory.setNamespaceAware(true);
//XML Pull Parser is an interface that defines parsing functionality provided in XMLPULL V1 API
//newPullParser is Creates a new instance of a XML Pull Parser using the currently configured factory features.
XmlPullParser xxp = factory.newPullParser();
xxp.setInput(new StringReader(xmlData));
//getEventType Returns the type of the current event (START_TAG, END_TAG, TEXT, etc.). return int
int eventType = xxp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
String tagName = xxp.getName();
switch (eventType) {
case XmlPullParser.START_TAG:
Log.d(TAG, "Parse: Starting tag for " + tagName);
if ("item".equalsIgnoreCase(tagName)) {
InEntry = true;
currentNews = new NewsFeeds();
}
break;
case XmlPullParser.TEXT:
textValue = xxp.getText();
break;
case XmlPullParser.END_TAG:
if (InEntry) {
if ("item".equalsIgnoreCase(tagName)) {
application.add(currentNews);
} else if ("title".equalsIgnoreCase(tagName)) {
currentNews.setName(textValue);
} else if ("pubdate".equalsIgnoreCase(tagName)) {
currentNews.setTheDate(textValue);
} else if ("description".equalsIgnoreCase(tagName)) {
currentNews.setSummry(textValue);
} else if ("link".equalsIgnoreCase(tagName)) {
currentNews.setTitle(textValue);
} else if ("enclosure".equalsIgnoreCase(tagName)) {
currentNews.setImageUrl(textValue);
}
}
break;
default:
//nothing to do
}
eventType = xxp.next();
}
for (NewsFeeds app : application) {
Log.d(TAG, "*********************");
Log.d(TAG, app.toString());
}
} catch (Exception e) {
status = false;
}
return status;
}
}**
i can't access the inner tag to get the image "url" here my tag name is "enclosure" and it contain another one called "url" and this is what i want to get... here the a whole class i created
I suggest printing the raw data and see the hierarchy of the tags. just do a Log without parsing the data and read it yourself. It might be missing or you need to access a parent tag before you get it.
also this might seem basic but are you sure you typed it correctly ? (capital letters, spaces etc)
How about the other tags ? I guess you are getting them correctly .
SOLVED
JUST TWO LINES
else if ("enclosure".equalsIgnoreCase(tagName)) {
String url = xxp.getAttributeValue(0);
currentNews.setImageUrl(url);
}
I have created dynamic link manually and i set some additional parameters on the link, like this: https://XXXXX.goo.gl/?link=https%3A%2F%2Fairbanq.send.com%2Fsendmoney&apn=com.xxxx.xxxx&amv=1&username=Adri&amount=7.00
But when the app is opened i just get: "https:// airbanq.send.com/sendmoney"
without the addiotional parameters
i am using this sample code
https://github.com/firebase/quickstart-android/tree/master/dynamiclinks
any help please,
Thanks
My code
public String buildDeepLink() {
// Get the unique appcode for this app.
String appCode = AirBanqApp.mContext.getString(R.string.app_code);
// Get this app's package name.
String packageName = AirBanqApp.mContext.getPackageName();
// Build the link with all required parameters
Uri.Builder builder = new Uri.Builder()
.scheme("https")
.authority(appCode + ".app.goo.gl")
.path("/")
.appendQueryParameter("link", deepLink)
.appendQueryParameter("apn", packageName);
// If the deep link is used in an advertisement, this value must be set to 1.
if (isAd) {
builder.appendQueryParameter("ad", "1");
}
// Minimum version is optional.
if (minVersion > 0) {
builder.appendQueryParameter("amv", Integer.toString(minVersion));
}
if (!TextUtils.isEmpty(androidLink)) {
builder.appendQueryParameter("al", androidLink);
}
if (!TextUtils.isEmpty(playStoreAppLink)) {
builder.appendQueryParameter("afl", playStoreAppLink);
}
if (!customParameters.isEmpty()) {
for (Map.Entry<String, String> parameter : customParameters.entrySet()) {
builder.appendQueryParameter(parameter.getKey(), parameter.getValue());
}
}
// Return the completed deep link.
return builder.build().toString();
}
Thats was my solution
i solved my issue, i assumed the "apn", "username" and "amount" they were part of the parameter "LINK" in the url, but no when i add the "&" i am adding parts to the main url, to add parameters to the "LINK" field i need to create first the url like this
https://airbanq.send.com/sendmoney?username=Adri&amount=7.00
then use URLEncoder.encode(queryParameters.toString(), "UTF-8");
to generate this
https%3A%2F%2Fairbanq.send.com%2Fsendmoney%253Fusername%253DAdri%2526amount%253D7.00
and then append to main url
https://xxxx.app.goo.gl/?link=https%3A%2F%2Fairbanq.send.com%2Fsendmoney%253Fusername%253DAdri%2526amount%253D7.00&apn=com.airbanq.airbanqapp&amv=1
public String buildDeepLink() {
// Get the unique appcode for this app.
String appCode = AirBanqApp.mContext.getString(R.string.app_code);
// Get this app's package name.
String packageName = AirBanqApp.mContext.getPackageName();
String queryParamters = "";
try {
queryParamters = generateQueryParameters();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (!TextUtils.isEmpty(queryParamters)) {
deepLink = deepLink + queryParamters;
}
// Build the link with all required parameters
Uri.Builder builder = new Uri.Builder()
.scheme("https")
.authority(appCode + ".app.goo.gl")
.path("/")
.appendQueryParameter("link", deepLink)
.appendQueryParameter("apn", packageName);
// If the deep link is used in an advertisement, this value must be set to 1.
if (isAd) {
builder.appendQueryParameter("ad", "1");
}
// Minimum version is optional.
if (minVersion > 0) {
builder.appendQueryParameter("amv", Integer.toString(minVersion));
}
if (!TextUtils.isEmpty(androidLink)) {
builder.appendQueryParameter("al", androidLink);
}
if (!TextUtils.isEmpty(playStoreAppLink)) {
builder.appendQueryParameter("afl", playStoreAppLink);
}
// Return the completed deep link.
return builder.build().toString();
}
private String generateQueryParameters() throws UnsupportedEncodingException {
StringBuilder queryParameters = new StringBuilder();
//server purposes
queryParameters.append("?*code*");
if (!customParameters.isEmpty()) {
for (Map.Entry<String, String> parameter : customParameters.entrySet()) {
queryParameters.append(String.format("&%1s=%2s", parameter.getKey(), parameter.getValue()));
}
}
return URLEncoder.encode(queryParameters.toString(), "UTF-8");
}
The official answer is that you need to escape/encode a URL string so that it can be safely placed inside a URL query.
I wish Firebase dynamic links would just say that about the link.
For Golang:
url.QueryEscape(urlstring)
I had this code working for the same site but they changed the theme and now i'm struggling. What could i be doing wrong here to get the url of the youtube video? Here's my approach. The example link of the site is http://kabumbu.co.tz/mahojiano-na-masau-bwire/
Element video = doc.select("div.single-archive iframe").first() ;
videourl = video.attr("src");
The code is correct so far but I just was wrongly extracting the video id from the video url. Using this method worked
public static String extractVideoId(String ytUrl) {
String vId = null;
Pattern pattern = Pattern.compile(".*(?:youtu.be\\/|v\\/|u\\/\\w\\/|embed\\/|watch\\?v=)([^#\\&\\?]*).*");
Matcher matcher = pattern.matcher(ytUrl);
if (matcher.matches()){
vId = matcher.group(1);
}
return vId;
}
Alternatively, here is a Jsoup only solution:
/**
*
* /!\ Exceptions raised by this method are NOT logged. /!\
*
* #param youtubeUrl
* #return videoId or null if an exception occured
*
*/
public static String extractVideoId(String youtubeUrl) {
String videoId = null;
try {
Document videoPage = Jsoup.connect(youtubeUrl).get();
Element videoIdMeta = videoPage.select("div[itemtype=http://schema.org/VideoObject] meta[itemprop=videoId]").first();
if (videoIdMeta == null) {
throw new IOException("Unable to find videoId in HTML content.");
}
videoId = videoIdMeta.attr("content");
} catch (Exception e) {
e.printStackTrace(); // alternatively you may log this exception...
}
return videoId;
}
The Best Way is
code =youtubeUrl.substring(youtubeUrl.length() - 11);
I am trying to encode a string which contains a URL, I have a strange issue where the complete string is not being returned, I have noticed that it may be related to the underscore, I have tried a few solution where I replace the underscore, but haven't had much luck with that solution. Below is the JSON.
[{"id":"1","source":"BBC WORLD NEWS",
"time_date":"Sat, 25 Oct 2014 10:49:13",
"title":"Iran hangs woman despite campaign","description":"Iran defies an international campaign and hangs a woman who killed a man she said was trying to sexually abuse her.",
"link":"http:\/\/www.bbc.co.uk\/news\/world-middle-east-29769468#sa-ns_mchannel=rss&ns_source=PublicRSS20-sa",
"image":"http:\/\/news.bbcimg.co.uk\/media\/images\/78529000\/jpg\/_78529517_78528720.jpg"},
I am trying to retrieve the image element from the json. The following is what I receive from my parsing.
http://news.bbcimg.co.uk/media/images/78526000/jpg
I am using this code at the moment:
String imageurl = feed.getImage();
try {
imageurl = URLDecoder.decode(imageurl, "UTF-8");
System.out.println("---------------------------"+imageurl);
imageurl.replace("_", "%5f");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
getimage method:
private String image;
public String getImage() {
return image;
}
private void requestNewsData(String uri) {
RestAdapter api = new RestAdapter.Builder().setEndpoint(ENDPOINT).build();
NewsAPI restapi = api.create(NewsAPI.class);
restapi.news(new Callback<List<RssObject>>() {
public void success(final List<RssObject> newsFeed, Response response) {
Log.v("nas", "the webservice success " + response.getReason());
for (int i = 0; i < newsFeed.size(); i++) {
System.out.println(newsFeed.get(i).description);
newsList.add(newsFeed.get(i).description);
FeederModel feed = new FeederModel();
feed.setSource(newsFeed.get(i).source);
feed.setImage(newsFeed.get(i).image); // adding setimage
}
}
The retrieved string is missing the final part of the url.
Any suggestion would be gratefully appreciated. Thanks.