Example usage for org.apache.commons.httpclient.util URIUtil encodeQuery

List of usage examples for org.apache.commons.httpclient.util URIUtil encodeQuery

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.util URIUtil encodeQuery.

Prototype

public static String encodeQuery(String unescaped) throws URIException 

Source Link

Document

Escape and encode a string regarded as the query component of an URI with the default protocol charset.

Usage

From source file:com.discursive.jccook.httpclient.QueryStringExample.java

public static void main(String[] args) throws HttpException, IOException {
    HttpClient client = new HttpClient();

    String url = "http://www.discursive.com/cgi-bin/jccook/param_list.cgi";

    // Set the Query String with setQueryString()
    HttpMethod method = new GetMethod(url);
    method.setQueryString(URIUtil.encodeQuery("test1=O'Reilly&blah=Whoop"));
    System.out.println("With Query String: " + method.getURI());
    client.executeMethod(method);//  w  w  w  .  j  a v  a 2  s.c o m
    System.out.println("Response:\n " + method.getResponseBodyAsString());
    method.releaseConnection();

    // Set query string with name value pair objects
    method = new GetMethod(url);
    NameValuePair pair = new NameValuePair("test2", URIUtil.encodeQuery("One & Two"));
    NameValuePair pair2 = new NameValuePair("param2", URIUtil.encodeQuery("TSCM"));
    NameValuePair[] pairs = new NameValuePair[] { pair, pair2 };
    method.setQueryString(pairs);
    System.out.println("With NameValuePairs: " + method.getURI());
    client.executeMethod(method);
    System.out.println("Response:\n " + method.getResponseBodyAsString());
    method.releaseConnection();
}

From source file:apm.common.utils.HttpTookit.java

/**
 * HTTP GET?HTML/*from  w  w  w .jav  a  2  s  .  c  om*/
 * 
 * @param url
 *            URL?
 * @param queryString
 *            ?,?null
 * @param charset
 *            
 * @param pretty
 *            ?
 * @return ?HTML
 */
public static String doGet(String url, String queryString, String charset, boolean pretty) {
    StringBuffer response = new StringBuffer();
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    try {
        if (StringUtils.isNotBlank(queryString))
            // get??http?????%?
            method.setQueryString(URIUtil.encodeQuery(queryString));
        client.executeMethod(method);
        if (method.getStatusCode() == HttpStatus.SC_OK) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(method.getResponseBodyAsStream(), charset));
            String line;
            while ((line = reader.readLine()) != null) {
                if (pretty) {
                    response.append(line).append(System.getProperty("line.separator"));
                } else {
                    response.append(line);
                }
            }
            reader.close();
        }
    } catch (URIException e) {
        log.error("HTTP Get?" + queryString + "???", e);
    } catch (IOException e) {
        log.error("HTTP Get" + url + "??", e);
    } finally {
        method.releaseConnection();
    }
    return response.toString();
}

From source file:de.innovationgate.utils.CookieValueEncoder.java

/**
 * Encodes the value/*from   ww  w  .ja  v  a  2  s . c  o  m*/
 * @param value Input value
 * @return Encoded value or null if not encodeable
 */
public static String encode(String value) {

    StringBuffer out = new StringBuffer();
    int len = value.length();
    for (int i = 0; i < len; i++) {
        char c = value.charAt(i);

        // Omit control characters completely
        if (c < 0x20 || c == 0x7f) {
            continue;
        }

        // Encode characters beyond ASCII plus the percent character
        if (c > 0x7f || c == '%') {
            try {
                out.append(URIUtil.encodeQuery(String.valueOf(c)));
            } catch (URIException e) {
                continue;
            }
            continue;
        }

        // Regular output
        out.append(c);

    }

    return out.toString();

}

From source file:eu.linda.analytics.db.ConnectionController.java

public String getQueryURI(String query_id) {
    String query_uri = null;//from w  ww  .  j ava 2s .c o  m

    try {
        Query linda_query = dbsynchronizer.getQueryURI(Integer.parseInt(query_id));

        //System.out.println("linda_query encoded" + URIUtil.encodeQuery(linda_query.getSparql()));
        query_uri = Configuration.rdf2anyServer + "/rdf2any/v1.0/convert/csv-converter.csv?dataset="
                + linda_query.getEndpoint() + "&query=" + URIUtil.encodeQuery(linda_query.getSparql());

    } catch (URIException ex) {
        Logger.getLogger(HelpfulFunctionsSingleton.class.getName()).log(Level.SEVERE, null, ex);
    }

    //System.out.println("query_uri" + query_uri);
    return query_uri;

}

From source file:fichiercentraltheses.AtomCaller.java

public void call() throws URIException {

    Abdera abdera = new Abdera();
    AbderaClient client = new AbderaClient(abdera);
    String searchString = "http://www.theses.fr/?q=&fq=dateSoutenance:[1965-01-01T23:59:59Z%2BTO%2B2013-12-31T23:59:59Z]&checkedfacets=role=auteur&format=atom";
    searchString = URIUtil.encodeQuery(searchString);
    ClientResponse resp = client.get(searchString);
    System.out.println("resp: " + resp.getStatusText());

    if (resp.getType() == ResponseType.SUCCESS) {
        Document docAbdera = resp.getDocument();
        Element elementAbdera = docAbdera.getRoot();

        System.out.println("response: " + elementAbdera.toString());

        Iterator<Element> elementIterator = elementAbdera.getElements().get(0).getElements().iterator();
        System.out.println("number of docs found: " + elementAbdera.getElements().get(0).getElements().size());

        //looping through the 19 items
        //            while (elementIterator.hasNext()) {
        //                NationaalArchiefDoc doc = new NationaalArchiefDoc();
        //                Element element1 = elementIterator.next();
        ////from   w ww . ja v a2 s .  c o m
        //                //looping through all elements of each item
        //                for (Element element2 : element1.getElements()) {
        //                    doc.getKeyValues().put(element2.getQName().getLocalPart(), element2.getText());
        //                    if (element2.getQName().getLocalPart().equals("subject")) {
        //                        System.out.println("element key: " + element2.getQName().getLocalPart());
        //                        System.out.println("element value: " + element2.getText());
        //                        System.out.println("");
        //                    }
        //                }
        //                docs.add(doc);
        //            }
    }
    //        return docs;
}

From source file:cz.incad.cdk.cdkharvester.PidsRetriever.java

private void getDocs() throws Exception {
    String urlStr = harvestUrl + URIUtil.encodeQuery(actual_date);
    logger.log(Level.INFO, "urlStr: {0}", urlStr);
    org.w3c.dom.Document solrDom = solrResults(urlStr);
    String xPathStr = "/response/result/@numFound";
    expr = xpath.compile(xPathStr);//from  ww w  .  j  a  v  a  2s  .  c  om
    int numDocs = Integer.parseInt((String) expr.evaluate(solrDom, XPathConstants.STRING));
    logger.log(Level.INFO, "numDocs: {0}", numDocs);
    if (numDocs > 0) {
        xPathStr = "/response/result/doc/str[@name='PID']";
        expr = xpath.compile(xPathStr);
        NodeList nodes = (NodeList) expr.evaluate(solrDom, XPathConstants.NODESET);
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            String pid = node.getFirstChild().getNodeValue();
            String to = node.getNextSibling().getFirstChild().getNodeValue();
            qe.add(new DocEntry(pid, to));
        }
    }
}

From source file:data.engine.request.builder.RequestBuilder.java

private String EncodeQuery(String query) {
    String str = "";
    try {/*from www .  ja  v  a  2s .  c o m*/
        str = URIUtil.encodeQuery(query);
    } catch (URIException ex) {
        System.out.println("Unable to encode request query " + ex.getStackTrace());
    }
    return str;
}

From source file:com.hbc.api.trade.ota.service.ThirdAPIService.java

/**
 * /*from   w w  w. j  av  a2  s.  c  om*/
 * @param params
 * @return
 * @since v1.0.1
 */
public OrderPriceInfo getPriceFromAPI(Map<String, String> params, OrderType orderType) {
    if (params == null || params.isEmpty())
        return null;

    Set<String> keySet = params.keySet();
    StringBuilder parstr = new StringBuilder();
    for (String keyStr : keySet) {
        String value = params.get(keyStr);
        if (value != null) {
            parstr.append("&").append(keyStr).append("=").append(value);
        }
    }
    try {
        return getPriceFromAPI(URIUtil.encodeQuery(parstr.toString().substring(1)), orderType);
    } catch (URIException e) {
        log.error("URL?", e);
        throw new TradeException(TradeReturnCodeEnum.ORDER_PARAM_FAILED, "");
    }
}

From source file:it.isti.cnr.hpc.europeana.hackthon.domain.GoogleQuery2Entity.java

public String produceQueryUrl(String query) {
    String queryUrl = "http://www.google.com/search?hl=en&source=hp&biw=1063&bih=569&q=" + query
            + "&aq=f&aqi=g10&aql=&oq=";
    // String queryUrl = "http://www.di.unipi.it/~ceccarel";
    String encodedQueryUrl;/*  w  w  w .j av  a  2 s.  co  m*/
    try {
        encodedQueryUrl = URIUtil.encodeQuery(queryUrl);
    } catch (URIException e) {
        logger.error("Error producing the enconded query for " + queryUrl);
        return null;
    }
    return encodedQueryUrl;
}

From source file:it.isti.cnr.hpc.europeana.hackthon.domain.FreebaseMapper.java

public static Freebase getInstanceFromQuery(String query)
        throws IOException, EntityException, NoResultException {
    KeyGenerator kg = new KeyGenerator();
    Integer key = kg.getKey(query);
    if (cache.containsKey(key))
        return cache.get(key);

    String uri = SuggestionProperties.getInstance().getProperty("freebase.query.api");
    uri += query;/*w  ww.j  a v a2 s. c o m*/

    try {
        uri = URIUtil.encodeQuery(uri);
    } catch (URIException e) {
        logger.error("Error producing the enconded query for {}", uri);
        return null;
    }
    try {
        URL u = new URL(uri);
        URLConnection uc = u.openConnection();

        InputStream is = uc.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        Freebase fb = parseFromJson(br);
        cache.put(key, fb);
        return fb;

    } catch (IOException e) {
        throw new IOException("error retrieving the query from freebase");

    }

}