How to get domain of example.co.ir in java [duplicate] - java

This question already has answers here:
Parsing result of URL.getHost()
(2 answers)
Closed 8 years ago.
I need to parse url in my java code and get the domain. I wrote the following code:
static String domain(URL url) {
String host = url.getHost();
int i = host.lastIndexOf('.');
if(i == -1){
return "Not domain";
}
if (i ==0 ){
return "Not domain";
}
String domain;
i = host.lastIndexOf('.', i - 1);
if (i == -1) {
domain = host;
}
else {
domain = host.substring(i + 1, host.length());
}
}
This code parses domains like example.com
But how can my code parse domains like exmaple.co.ir , subdomains.example.co.ir and the others extensions like co.uk, org.ir and so on.
EDIT
my url is http//blog.example.co.ir/index.php or http//blog.example.co.uk/something.html
my goal is to print:
example.co.ir and example.co.uk

The problem is that your parsing code is limited to domains with just one dot. You can use regular expressions or recursive parsing to solve this problem. This is one way of approaching this problem.

I believe this work for any kind of URL(in correct URL format)
domain= host.split("/")[2];
Note:
split("/") will create an array from the String, for example:
String host="http//blog.example.co.ir/index.php";
host.split("/") will give you array of String: [http, ,blog.example.co.ir, index.php]
And your desired output is at index 2

Related

Java url parsing [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 5 years ago.
Okay so I'm trying to parse the url and extract partial data.. However it doesn't seem to be extracting the exact data I want.. I assume it's extracting ID and not Value.
This is the code I'm using
price = readUrl(apiUrl + String.valueOf(id)).split(",")[1].split(":")[1];
String price2 = price.substring(0, price.length() - 1);
return Integer.parseInt(price2);
the url I'm using is
https://api.rsbuddy.com/grandExchange?a=guidePrice&i=
parameter i = id of item, for this example we will use " 2619 "
which returns,
{"overall":49907,"buying":0,"buyingQuantity":0,"selling":49907,"sellingQuantity":2}
the information I want is
49907
from
{"overall":49907,
Use JSONObject:
JSONObject jsonObject = new JSONObject(YOUR_STRING_YOU_WANT_TO_PARSE);
Integer price = jsonObject.getInt("overall");
What you get from API is a JSON. So you can simply use JSONObject.
https://docs.oracle.com/javaee/7/api/javax/json/JsonObject.html
You can do something like:
jsonObject.getInt("overall");

How can I get parameters from URL in Android? [duplicate]

This question already has answers here:
How to parse or split URL Address in Java?
(4 answers)
Closed 6 years ago.
I have a URL like this:
http://www.chalklit.in/post.html?chapter=V-Maths-Addition%20&%20Subtraction&post=394
How to get the value of parameter of chapter and post?
My URL contains '&' in the value of chapter parameter.
You can use the Uri class in Android to do this; https://developer.android.com/reference/android/net/Uri.html
Uri uri = Uri.parse("http://www.chalklit.in/post.html?chapter=V-Maths-Addition%20&%20Subtraction&post=394");
String server = uri.getAuthority();
String path = uri.getPath();
String protocol = uri.getScheme();
Set<String> args = uri.getQueryParameterNames();
Then you can even get a specific element from the query parameters as such;
String chapter = uri.getQueryParameter("chapter"); //will return "V-Maths-Addition "

How to read the public URL in GWT?

I m new in GWT and I m generating a web application in which i have to create a public URL.
In this public URL i have to pass hashtag(#) and some parameters.
I am finding difficulty in achieving this task.
Extracting the hashtag from the URL.
Extracting the userid from the URL.
My public URL example is :: http://www.xyz.com/#profile?userid=10003
To access the URL in GWT you can use the History.getToken() method. It will give you the entire string that follows the hashtag ("#").
In your case (http://www.xyz.com/#profile?userid=10003) it will return a string "profile?userid=10003". After you have this you can parse it however you want. You can check if it contains("?") and u can split it by "?" or you can get a substring. How you get the information from that is really up to you.
I guess you already have the URL. I'm not that good at Regex, but this should work:
String yourURL = "http://www.xyz.com/#profile?userid=10003";
String[] array = yourURL.split("[\\p{Lower}\\p{Upper}\\p{Punct}}]");
int userID = 0;
for (String string : array) {
if (!string.isEmpty()) {
userID = Integer.valueOf(string);
}
}
System.out.println(userID);
To get the parameters:
String userId = Window.Location.getParameter("userid");
To get the anchor / hash tag:
I don't think there is something, you can parse the URL: look at the methods provided by Window.Location.

Get request parameter with Play Framework?

I am learning play framework and understand that I can map a request such as /manager/user as:
GET /manage/:user Controllers.Application.some(user:String)
How would I map a request like /play/video?video_id=1sh1?
You have at least two possibilities, let's call them approach1 and approach2.
In the first approach you can declare a routes param with some default value. 0 is good candidate, as it will be easiest to build some condition on top of it. Also it's typesafe, and pre-validates itself. I would recommend this solution at the beginning.
Second approach reads params directly from request as a String so you need to parse it to integer and additionally validate if required.
routes:
GET /approach1 controllers.Application.approach1(video_id: Int ?=0)
GET /approach2 controllers.Application.approach2
actions:
public static Result approach1(int video_id) {
if (video_id == 0) return badRequest("Wrong video ID");
return ok("1: Display video no. " + video_id);
}
public static Result approach2() {
int video_id = 0;
if (form().bindFromRequest().get("video_id") != null) {
try {
video_id = Integer.parseInt(form().bindFromRequest().get("video_id"));
} catch (Exception e) {
Logger.error("int not parsed...");
}
}
if (video_id == 0) return badRequest("Wrong video ID");
return ok("2: Display video no. " + video_id);
}
PS: LOL I just realized that you want to use String identifier... anyway both approaches will be similar :)
I would do it simply using:
GET /play/video Controllers.Application.video(video_id:String)
And at controller you would of course have, something like:
public static Result video(String video_id) {
return ok("We got video id of: " + video_id);
}
Alternatively, you dont have to add video_id:String since play seems to treat parameters as String by default, so it also works like this (at least with newest play):
GET /play/video Controllers.Application.video(video_id)
Typing localhost:9000/play/video?video_id=1sh1 to address bar should now you give view which prints:
We got video id of: 1sh1
To add more parameters is simple, like this:
GET /play/video controllers.Application.video(video_id:String, site:String, page:Integer)
Controller:
public static Result video(String video_id, String site, Integer page) {
return ok("We got video id of: " + video_id + " site: " + site + " page: " + page);
}
Typing localhost:9000/play/video?video_id=1as1&site=www.google.com&page=3 to address bar should now you give view which prints:
We got video id of: 1as1 site: www.google.com page: 3
You're welcome ^^.
I'm not quite sure if I got what you meant if you meant just to map a url to function in controller the answer of biesior is perfect but if you mean submitting a form with get method like
#helper.form(action = routes.YourController.page1()) {
}
and having the form's parameter in the url in the url-rewrited format like
page1/foo/bar instead of page1?param1=foo&param2=bar
There is no way to do that because that's http specs
I do often circumvent this limitation by getting the parameters in the first function in controller and then redirect them to another view just like the following
public static Result page1(){
String param1 = Form.form().bindFromRequest().get("param1");
String param2= Form.form().bindFromRequest().get("param2");
return ( redirect( routes.YourController.page2(param1,param2)));
}
Then have whatever in the page2
public static Result page2(String param1,String param2){
...............
}
And have this in the routes file :
GET page2/:param1/:param2 controllers.YourControllers.page2(param1 : String, param2 : String )
I hope it'd help but I'm not sure that's the best practise
Ok so I just read up the documentation and what I understand is that you need to
GET /play/video Controllers.Application.video()
And then in the controller call the getQueryString of the HttpRequest object
http://www.playframework.com/documentation/api/2.1.0/java/index.html

url harvester string manipulation

I'm doing a recursive url harvest.. when I find an link in the source that doesn't start with "http" then I append it to the current url. Problem is when I run into a dynamic site the link without an http is usually a new parameter for the current url. For example if the current url is something like http://www.somewebapp.com/default.aspx?pageid=4088 and in the source for that page there is a link which is default.aspx?pageid=2111. In this case I need do some string manipulation; this is where I need help.
pseudocode:
if part of the link found is a contains a substring of the current url
save the substring
save the unique part of the link found
replace whatever is after the substring in the current url with the unique saved part
What would this look like in java? Any ideas for doing this differently? Thanks.
As per comment, here's what I've tried:
if (!matched.startsWith("http")) {
String[] splitted = url.toString().split("/");
java.lang.String endOfURL = splitted[splitted.length-1];
boolean b = false;
while (!b && endOfURL.length() > 5) { // f.bar shortest val
endOfURL = endOfURL.substring(0, endOfURL.length()-2);
if (matched.contains(endOfURL)) {
matched = matched.substring(endOfURL.length()-1);
matched = url.toString().substring(url.toString().length() - matched.length()) + matched;
b = true;
}
}
it's not working well..
I think you are doing this the wrong way. Java has two classes URL and URI which are capable of parsing URL/URL strings much more accurately than a "string bashing" solution. For example the URL constructor URL(URL, String) will create a new URL object in the context of an existing one, without you needing to worry whether the String is an absolute URL or a relative one. You would use it something like this:
URL currentPageUrl = ...
String linkUrlString = ...
// (Exception handling not included ...)
URL linkUrl = new URL(currentPageUrl, linkUrlString);

Categories

Resources