Getting URL parameter in java and extract a specific text from that URL
Asked Answered
K

13

40

I have a URL and I need to get the value of v from this URL. Here is my URL: http://www.youtube.com/watch?v=_RCIP6OrQrE

How can I do that?

Kindig answered 31/7, 2012 at 5:14 Comment(6)
what is v ?? and please provide some more information and code if you canCathern
what you are trying to do with youtube URL ? do you need to find the value v from a url-string using substring methods ?Maduro
youtube.com/watch?v=_RCIP6OrQrE I need to get value of v=Kindig
@androidmaniac look at my answer it only return idCathern
@androidmaniac hey android, check out my answer btw.. I rewrote it. The function will support multiple sets of youtube urls.Abscind
@androidmaniac I updated my answer, by the way.. the code represents a more universal way of retrieving a parameter from any youtube url.Abscind
M
74

I think the one of the easiest ways out would be to parse the string returned by URL.getQuery() as

public static Map<String, String> getQueryMap(String query) {  
    String[] params = query.split("&");  
    Map<String, String> map = new HashMap<String, String>();

    for (String param : params) {  
        String name = param.split("=")[0];  
        String value = param.split("=")[1];  
        map.put(name, value);  
    }  
    return map;  
}

You can use the map returned by this function to retrieve the value keying in the parameter name.

Microscopy answered 31/7, 2012 at 5:31 Comment(5)
This would not work for multivalued parameters. In the following example the EmployeeID parameter has three values: Northwest/Employee Sales Report&rs:Command=Render&EmployeeID=A&EmployeeID=B&EmployeeID=C You could make this work using a multi-valule map implementation instead of HashMap. I don't think the JRE has any, but multi-value map parameter implementations are easily found on the web.Macur
Also a ArrayIndexOutOfBoudndsException would be throw for urls like example.com.com?param or example.com?param=Aloisia
I recommend the solution here: #5902590Aloisia
This will not work if the values contain "=" signs. I changed String value = param.split("=")[1]; with String value = param.split(name+"=")[1]; and now it seems to work.Prosper
what if the param1=H&M, it doesn't parse if the parameter value itself has an ampersand(&)Terrell
B
30

If you're on Android, you can do this:

Uri uri = Uri.parse(url);
String v = uri.getQueryParameter("v");
Bacciferous answered 8/11, 2016 at 2:18 Comment(2)
Could you explain what package contains this?Mcginley
@TJ It's in the Android SDKTakeover
E
9

I have something like this:

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URIBuilder;

private String getParamValue(String link, String paramName) throws URISyntaxException {
        List<NameValuePair> queryParams = new URIBuilder(link).getQueryParams();
        return queryParams.stream()
                .filter(param -> param.getName().equalsIgnoreCase(paramName))
                .map(NameValuePair::getValue)
                .findFirst()
                .orElse("");
    }
Epiphytotic answered 11/7, 2017 at 14:26 Comment(0)
A
3

I wrote this last month for Joomla Module when implementing youtube videos (with the Gdata API). I've since converted it to java.

Import These Libraries

    import java.net.URL;
    import java.util.regex.*;

Copy/Paste this function

    public String getVideoId( String videoId ) throws Exception {
        String pattern = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(videoId);
        int youtu = videoId.indexOf("youtu");
        if(m.matches() && youtu != -1){
            int ytu = videoId.indexOf("http://youtu.be/");
            if(ytu != -1) { 
                String[] split = videoId.split(".be/");
                return split[1];
            }
            URL youtube = new URL(videoId);
            String[] split = youtube.getQuery().split("=");
            int query = split[1].indexOf("&");
            if(query != -1){
                String[] nSplit = split[1].split("&");
                return nSplit[0];
            } else return split[1];
        }
        return null; //throw something or return what you want
    }

URL's it will work with

http://www.youtube.com/watch?v=k0BWlvnBmIE (General URL)
http://youtu.be/k0BWlvnBmIE (Share URL)
http://www.youtube.com/watch?v=UWb5Qc-fBvk&list=FLzH5IF4Lwgv-DM3CupM3Zog&index=2 (Playlist URL)
Abscind answered 31/7, 2012 at 5:17 Comment(3)
You should use Arrays.toString(tokens).Clangor
@paranoid-android +1 rep yeah thanks I know, just forgot what the syntax was without Eclipse open.Abscind
Please don't advocate parsing URLs by hand. Use a library for that.Fit
S
3

Import these libraries

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

Similar to the verisimilitude, but with the capabilities of handling multivalue parameters. Note: I've seen HTTP GET requests without a value, in this case the value will be null.

public static List<NameValuePair> getQueryMap(String query)  
{  
    List<NameValuePair> queryMap = new ArrayList<NameValuePair>();
    String[] params = query.split(Pattern.quote("&"));  
    for (String param : params)
    {
        String[] chunks = param.split(Pattern.quote("="));
        String name = chunks[0], value = null;  
        if(chunks.length > 1) {
            value = chunks[1];
        }
        queryMap.add(new BasicNameValuePair(name, value));
    }
    return queryMap;
}

Example:

GET /bottom.gif?e235c08=1509896923&%49%6E%...
Stellate answered 23/4, 2015 at 7:4 Comment(0)
W
3

Using pure Java 8

Assumming you want to extract param "v" from url:

             String paramV = Stream.of(url.split("?")[1].split("&"))
                        .map(kv -> kv.split("="))
                        .filter(kv -> "v".equalsIgnoreCase(kv[0]))
                        .map(kv -> kv[1])
                        .findFirst()
                        .orElse("");
Wright answered 21/7, 2020 at 15:29 Comment(0)
T
2

I believe we have a better approach to answer this question.

1: Define a function that returns Map values.

Here we go.

public Map<String, String> getUrlValues(String url) throws UnsupportedEncodingException {
    int i = url.indexOf("?");
    Map<String, String> paramsMap = new HashMap<>();
    if (i > -1) {
        String searchURL = url.substring(url.indexOf("?") + 1);
        String params[] = searchURL.split("&");

        for (String param : params) {
            String temp[] = param.split("=");
            paramsMap.put(temp[0], java.net.URLDecoder.decode(temp[1], "UTF-8"));
        }
    }

    return paramsMap;
}

2: Call your function surrounding with a try catch block

Here we go

try {
     Map<String, String> values = getUrlValues("https://example.com/index.php?form_id=9&page=1&view_id=78");
     String formId = values.get("form_id");
     String page = values.get("page");
     String viewId = values.get("view_id");
     Log.d("FormID", formId);
     Log.d("Page", page);
     Log.d("ViewID", viewId);
} catch (UnsupportedEncodingException e) {
     Log.e("Error", e.getMessage());
} 
Tremendous answered 16/3, 2019 at 7:7 Comment(0)
B
2

If you are using Jersey (which I was, my server component needs to make outbound HTTP requests) it contains the following public method:

var multiValueMap = UriComponent.decodeQuery(uri, true);

It is part of org.glassfish.jersey.uri.UriComponent, and the javadoc is here. Whilst you may not want all of Jersey, it is part of the Jersey common package which isn't too bad on dependencies...

Bax answered 29/3, 2019 at 16:36 Comment(0)
T
2

I solved the problem like this

public static String getUrlParameterValue(String url, String paramName) {
String value = "";
List<NameValuePair> result = null;

try {
    result = URLEncodedUtils.parse(new URI(url), UTF_8);
    value = result.stream().filter(pair -> pair.getName().equals(paramName)).findFirst().get().getValue();
    System.out.println("-------------->  \n" + paramName + " : " + value + "\n");
} catch (URISyntaxException e) {
    e.printStackTrace();
} 
return value;

}

Telespectroscope answered 27/10, 2019 at 9:9 Comment(0)
C
1

Assuming the URL syntax will always be http://www.youtube.com/watch?v= ...

String v = "http://www.youtube.com/watch?v=_RCIP6OrQrE".substring(31);

or disregarding the prefix syntax:

String url = "http://www.youtube.com/watch?v=_RCIP6OrQrE";
String v = url.substring(url.indexOf("v=") + 2);
Clangor answered 31/7, 2012 at 5:27 Comment(2)
What do you mean, @smonff?Clangor
I mean that I appreciated the simplicity of your answer :-DBeer
C
0

this will work for all sort of youtube url :
if url could be

youtube.com/?v=_RCIP6OrQrE
youtube.com/v/_RCIP6OrQrE
youtube.com/watch?v=_RCIP6OrQrE
youtube.com/watch?v=_RCIP6OrQrE&feature=whatever&this=that

Pattern p = Pattern.compile("http.*\\?v=([a-zA-Z0-9_\\-]+)(?:&.)*");
String url = "http://www.youtube.com/watch?v=_RCIP6OrQrE";
Matcher m = p.matcher(url.trim()); //trim to remove leading and trailing space if any

if (m.matches()) {
    url = m.group(1);        
}
System.out.println(url);

this will extract video id from your url

further reference

Cathern answered 31/7, 2012 at 5:33 Comment(0)
V
0

My solution mayble not good

        String url = "https://www.youtube.com/watch?param=test&v=XcHJMiSy_1c&lis=test";
        int start = url.indexOf("v=")+2;
        // int start = url.indexOf("list=")+5; **5 is length of ("list=")**
        int end = url.indexOf("&", start);

        end = (end == -1 ? url.length() : end); 

        System.out.println(url.substring(start, end));
        // result: XcHJMiSy_1c

work fine with:

  • https://www.youtube.com/watch?param=test&v=XcHJMiSy_1c&lis=test
  • https://www.youtube.com/watch?v=XcHJMiSy_1c
Verbenia answered 13/5, 2014 at 5:23 Comment(0)
B
0
public static String getQueryMap(String query) {        
    String[] params = query.split("&");     
    for (String param : params) {           
       String name = param.split("=")[0];
       if ("YourParam".equals(name)) {
           return param.split("=")[1]; 
       }
    }
    return null;
}
Bonnell answered 14/2, 2020 at 4:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.