Example usage for java.net URL getQuery

List of usage examples for java.net URL getQuery

Introduction

In this page you can find the example usage for java.net URL getQuery.

Prototype

public String getQuery() 

Source Link

Document

Gets the query part of this URL .

Usage

From source file:com.mobli.android.Util.java

/**
 * Parse a URL query and fragment parameters into a key-value bundle.
 * /*ww  w .  j av  a 2s .  c  om*/
 * @param url
 *            the URL to parse
 * @return a dictionary bundle of keys and values
 */
public static Bundle parseUrl(String url) {

    try {
        URL u = new URL(url);
        Bundle b = decodeUrl(u.getQuery());
        b.putAll(decodeUrl(u.getRef()));
        return b;
    } catch (MalformedURLException e) {
        return new Bundle();
    }
}

From source file:ie.wombat.rt.fireeagle.CookieConsumer.java

/** Reconstruct the requested URL path, complete with query string (if any). */
private static String getRequestPath(HttpServletRequest request) throws MalformedURLException {

    URL url = new URL(OAuthServlet.getRequestURL(request));
    StringBuilder path = new StringBuilder(url.getPath());
    String queryString = url.getQuery();
    if (queryString != null) {
        path.append("?").append(queryString);
    }//ww  w  . j  a va  2s . c  o m
    return path.toString();
}

From source file:net.greghaines.ghorgbrowser.service.impl.RetrofitGitHubService.java

private static Integer findLastPage(final Response response) throws MalformedURLException {
    Header linkHeader = null;//w ww  .  j  a  v a2s.c om
    for (final Header header : response.getHeaders()) {
        if ("Link".equals(header.getName())) {
            linkHeader = header;
            break;
        }
    }
    Integer lastPage = null;
    if (linkHeader != null) {
        final String[] rels = COMMA_PATTERN.split(linkHeader.getValue());
        for (final String rel : rels) {
            final String[] relParts = SEMICOLON_PATTERN.split(rel);
            final String relType = EQUAL_PATTERN.split(relParts[1].trim())[1].trim();
            if ("\"last\"".equals(relType)) {
                final String linkUrl = relParts[0].trim();
                final URL url = new URL(linkUrl.substring(1, linkUrl.length()));
                final MultiMap<String> params = new MultiMap<String>();
                UrlEncoded.decodeTo(url.getQuery(), params, StandardCharsets.UTF_8, 10);
                final String pageStr = params.getValue("page", 0);
                if (pageStr != null) {
                    lastPage = Integer.valueOf(pageStr);
                }
                break;
            }
        }
    }
    return lastPage;
}

From source file:org.apache.jmeter.protocol.http.util.ConversionUtils.java

/**
 * @param url String Url to escape/*from  ww  w .j ava 2s . co m*/
 * @return String cleaned up url
 * @throws Exception when given <code>url</code> leads to a malformed URL or URI
 */
public static String escapeIllegalURLCharacters(String url) throws Exception {
    String decodeUrl = URLDecoder.decode(url, "UTF-8");
    URL urlString = new URL(decodeUrl);
    URI uri = new URI(urlString.getProtocol(), urlString.getUserInfo(), urlString.getHost(),
            urlString.getPort(), urlString.getPath(), urlString.getQuery(), urlString.getRef());
    return uri.toString();
}

From source file:com.base.httpclient.HttpJsonClient.java

/**
 * get//from   w w w . ja  v a 2  s  .  c o m
 * 
 * @param url
 *            URL
 * @param params
 *            getkey-value
 * @return JSON
 * @throws ClientProtocolException
 * @throws IOException
 * @throws URISyntaxException 
 */
public static String get(String url, Map<String, ?> params)
        throws ClientProtocolException, IOException, URISyntaxException {
    DefaultHttpClient httpclient = getHttpClient();
    try {
        if (params != null && !(params.isEmpty())) {
            List<NameValuePair> values = new ArrayList<NameValuePair>();
            for (Map.Entry<String, ?> entity : params.entrySet()) {
                BasicNameValuePair pare = new BasicNameValuePair(entity.getKey(), entity.getValue().toString());
                values.add(pare);

            }
            String str = URLEncodedUtils.format(values, "UTF-8");
            if (url.indexOf("?") > -1) {
                url += "&" + str;
            } else {
                url += "?" + str;
            }
        }
        URL pageURL = new URL(url);
        //pageUrl?httpget
        URI uri = new URI(pageURL.getProtocol(), pageURL.getHost(), pageURL.getPath(), pageURL.getQuery(),
                null);
        HttpGet httpget = createHttpUriRequest(HttpMethod.GET, uri);
        httpget.setHeader("Pragma", "no-cache");
        httpget.setHeader("Cache-Control", "max-age=0, no-cache, no-store, must-revalidate");
        httpget.setHeader("Connection", "keep-alive");
        httpget.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        httpget.setHeader("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
        httpget.setHeader("Accept-Charset", "gbk,utf-8;q=0.7,*;q=0.7");
        httpget.setHeader("Referer", url);
        /*httpget.setHeader("Content-Encoding", "gzip");
        httpget.setHeader("Accept-Encoding", "gzip, deflate");*/
        //httpget.setHeader("Host", "s.taobao.com");
        /*int temp = Integer.parseInt(Math.round(Math.random()*(MingSpiderService.UserAgent.length-1))+"");//???
        httpget.setHeader("User-Agent", MingSpiderService.UserAgent[temp]);*/
        HttpResponse response = httpclient.execute(httpget);
        httpclient.getCookieStore().clear();
        int resStatu = response.getStatusLine().getStatusCode();
        String html = "";
        if (resStatu == HttpStatus.SC_OK) {//200 
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                html = EntityUtils.toString(entity, "GBK");
                EntityUtils.consume(entity);
            }
        }
        return html;
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:cn.bidaround.ytcore.kaixin.KaixinUtil.java

/**
 * URL??key-value??//from  w ww.  j  av a 2  s  .co  m
 * 
 * @param url
 *            ?url
 * @return key-value??
 */
public static Bundle parseUrl(String url) {
    url = url.replace("#", "?");
    try {
        URL u = new URL(url);
        Bundle b = decodeUrl(u.getQuery());
        Bundle ref = decodeUrl(u.getRef());
        if (ref != null)
            b.putAll(ref);
        return b;
    } catch (MalformedURLException e) {
        return new Bundle();
    }
}

From source file:com.magnet.plugin.helpers.UrlParser.java

public static ParsedUrl parseUrl(String url) {
    List<PathPart> pathParts = new ArrayList<PathPart>();
    List<Query> queries = new ArrayList<Query>();
    ParsedUrl parsedUrl;//w w  w . ja  va 2  s . c o  m
    String base;

    try {
        URL aURL = new URL(url);
        base = aURL.getAuthority();
        String protocol = aURL.getProtocol();
        parsedUrl = new ParsedUrl();
        parsedUrl.setPathWithEndingSlash(aURL.getPath().endsWith("/"));
        parsedUrl.setBase(protocol + "://" + base);
        List<NameValuePair> pairs = URLEncodedUtils.parse(aURL.getQuery(), Charset.defaultCharset());
        for (NameValuePair pair : pairs) {
            Query query = new Query(pair.getName(), pair.getValue());
            queries.add(query);
        }
        parsedUrl.setQueries(queries);

        String[] pathStrings = aURL.getPath().split("/");
        for (String pathPart : pathStrings) {
            Matcher m = PATH_PARAM_PATTERN.matcher(pathPart);
            if (m.find()) {
                String paramDef = m.group(1);
                String[] paramParts = paramDef.split(":");
                if (paramParts.length > 1) {
                    pathParts.add(new PathPart(paramParts[1].trim(), paramParts[0].trim()));
                } else {
                    pathParts.add(new PathPart(paramParts[0].trim()));
                }
            } else {
                if (!pathPart.isEmpty()) {
                    pathParts.add(new PathPart(pathPart));
                }
            }
        }
        parsedUrl.setPathParts(pathParts);
    } catch (Exception ex) {
        Logger.error(UrlParser.class, "Can't parse URL " + url);
        return null;
    }
    return parsedUrl;
}

From source file:com.magnet.plugin.r2m.helpers.UrlParser.java

public static ParsedUrl parseUrl(String url) {
    List<PathPart> pathParts = new ArrayList<PathPart>();
    List<Query> queries = new ArrayList<Query>();
    ParsedUrl parsedUrl;// w  w w .j  a  v a  2s.  c o m
    String base;

    try {
        URL aURL = new URL(url);
        base = aURL.getAuthority();
        String protocol = aURL.getProtocol();
        parsedUrl = new ParsedUrl();
        parsedUrl.setPathWithEndingSlash(aURL.getPath().endsWith("/"));
        parsedUrl.setBaseUrl(protocol + "://" + base);
        List<NameValuePair> pairs = URLEncodedUtils.parse(aURL.getQuery(), Charset.defaultCharset());
        for (NameValuePair pair : pairs) {
            Query query = new Query(pair.getName(), pair.getValue());
            queries.add(query);
        }
        parsedUrl.setQueries(queries);

        String[] pathStrings = aURL.getPath().split("/");
        for (String pathPart : pathStrings) {
            Matcher m = PATH_PARAM_PATTERN.matcher(pathPart);
            if (m.find()) {
                String paramDef = m.group(1);
                String[] paramParts = paramDef.split(":");
                if (paramParts.length > 1) {
                    pathParts.add(new PathPart(paramParts[1].trim(), paramParts[0].trim()));
                } else {
                    pathParts.add(new PathPart(paramParts[0].trim()));
                }
            } else {
                if (!pathPart.isEmpty()) {
                    pathParts.add(new PathPart(pathPart));
                }
            }
        }
        parsedUrl.setPathParts(pathParts);
    } catch (Exception ex) {
        Logger.error(UrlParser.class, R2MMessages.getMessage("CANNOT_PARSE_URL", url));
        return null;
    }
    return parsedUrl;
}

From source file:eu.trentorise.smartcampus.protocolcarrier.Communicator.java

private static HttpRequestBase buildRequest(MessageRequest msgRequest, String appToken, String authToken)
        throws URISyntaxException, UnsupportedEncodingException {
    String host = msgRequest.getTargetHost();
    if (host == null)
        throw new URISyntaxException(host, "null URI");
    if (!host.endsWith("/"))
        host += '/';
    String address = msgRequest.getTargetAddress();
    if (address == null)
        address = "";
    if (address.startsWith("/"))
        address = address.substring(1);//from www  .  j  a v  a 2s  .  c  o  m
    String uriString = host + address;
    try {
        URL url = new URL(uriString);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        uriString = uri.toURL().toString();
    } catch (MalformedURLException e) {
        throw new URISyntaxException(uriString, e.getMessage());
    }
    if (msgRequest.getQuery() != null)
        uriString += "?" + msgRequest.getQuery();

    //      new URI(uriString);

    HttpRequestBase request = null;
    if (msgRequest.getMethod().equals(Method.POST)) {
        HttpPost post = new HttpPost(uriString);
        HttpEntity httpEntity = null;
        if (msgRequest.getRequestParams() != null) {
            // if body and requestparams are either not null there is an
            // exception
            if (msgRequest.getBody() != null && msgRequest != null) {
                throw new IllegalArgumentException("body and requestParams cannot be either populated");
            }
            httpEntity = new MultipartEntity();

            for (RequestParam param : msgRequest.getRequestParams()) {
                if (param.getParamName() == null || param.getParamName().trim().length() == 0) {
                    throw new IllegalArgumentException("paramName cannot be null or empty");
                }
                if (param instanceof FileRequestParam) {
                    FileRequestParam fileparam = (FileRequestParam) param;
                    ((MultipartEntity) httpEntity).addPart(param.getParamName(), new ByteArrayBody(
                            fileparam.getContent(), fileparam.getContentType(), fileparam.getFilename()));
                }
                if (param instanceof ObjectRequestParam) {
                    ObjectRequestParam objectparam = (ObjectRequestParam) param;
                    ((MultipartEntity) httpEntity).addPart(param.getParamName(),
                            new StringBody(convertObject(objectparam.getVars())));
                }
            }
            // mpe.addPart("file",
            // new ByteArrayBody(msgRequest.getFileContent(), ""));
            // post.setEntity(mpe);
        }
        if (msgRequest.getBody() != null) {
            httpEntity = new StringEntity(msgRequest.getBody(), Constants.CHARSET);
            ((StringEntity) httpEntity).setContentType(msgRequest.getContentType());
        }
        post.setEntity(httpEntity);
        request = post;
    } else if (msgRequest.getMethod().equals(Method.PUT)) {
        HttpPut put = new HttpPut(uriString);
        if (msgRequest.getBody() != null) {
            StringEntity se = new StringEntity(msgRequest.getBody(), Constants.CHARSET);
            se.setContentType(msgRequest.getContentType());
            put.setEntity(se);
        }
        request = put;
    } else if (msgRequest.getMethod().equals(Method.DELETE)) {
        request = new HttpDelete(uriString);
    } else {
        // default: GET
        request = new HttpGet(uriString);
    }

    Map<String, String> headers = new HashMap<String, String>();

    // default headers
    if (appToken != null) {
        headers.put(RequestHeader.APP_TOKEN.toString(), appToken);
    }
    if (authToken != null) {
        // is here for compatibility
        headers.put(RequestHeader.AUTH_TOKEN.toString(), authToken);
        headers.put(RequestHeader.AUTHORIZATION.toString(), "Bearer " + authToken);
    }
    headers.put(RequestHeader.ACCEPT.toString(), msgRequest.getContentType());

    if (msgRequest.getCustomHeaders() != null) {
        headers.putAll(msgRequest.getCustomHeaders());
    }

    for (String key : headers.keySet()) {
        request.addHeader(key, headers.get(key));
    }

    return request;
}

From source file:org.talend.updates.runtime.utils.PathUtils.java

public static File getStudioConfigFile() throws Exception {
    URL configLocation = new URL("platform:/config/config.ini"); //$NON-NLS-1$
    URL fileUrl = FileLocator.toFileURL(configLocation);
    return URIUtil.toFile(new URI(fileUrl.getProtocol(), fileUrl.getPath(), fileUrl.getQuery()));
}