Example usage for org.apache.commons.httpclient HttpMethod setQueryString

List of usage examples for org.apache.commons.httpclient HttpMethod setQueryString

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod setQueryString.

Prototype

public abstract void setQueryString(NameValuePair[] paramArrayOfNameValuePair);

Source Link

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  ww . j  a v a 2 s .c  om*/
    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:com.github.jobs.api.GithubJobsApi.java

private static String createUrl(String url, List<NameValuePair> pairs) throws URIException {
    HttpMethod method = new GetMethod(url);
    NameValuePair[] nameValuePairs = pairs.toArray(new NameValuePair[pairs.size()]);
    method.setQueryString(nameValuePairs);
    return method.getURI().getEscapedURI();
}

From source file:com.alta189.cyborg.commit.ShortUrlService.java

public static String shorten(String url, String keyword) {
    switch (service) {
    case BIT_LY://from  w w w. j  av a 2s .c  om
        HttpClient httpclient = new HttpClient();
        HttpMethod method = new GetMethod("http://api.bit.ly/shorten");
        method.setQueryString(
                new NameValuePair[] { new NameValuePair("longUrl", url), new NameValuePair("version", "2.0.1"),
                        new NameValuePair("login", user), new NameValuePair("apiKey", apiKey),
                        new NameValuePair("format", "xml"), new NameValuePair("history", "1") });
        try {
            httpclient.executeMethod(method);
            String responseXml = method.getResponseBodyAsString();
            String retVal = null;
            if (responseXml != null) {
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                StringReader st = new StringReader(responseXml);
                Document d = db.parse(new InputSource(st));
                NodeList nl = d.getElementsByTagName("shortUrl");
                if (nl != null) {
                    Node n = nl.item(0);
                    retVal = n.getTextContent();
                }
            }

            return retVal;
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
        return null;
    case SPOUT_IN:
        HttpClient client = new HttpClient();
        String result = null;
        client.getParams().setParameter("http.useragent", "Test Client");

        BufferedReader br = null;
        PostMethod pMethod = new PostMethod("http://spout.in/yourls-api.php");
        pMethod.addParameter("signature", apiKey);
        pMethod.addParameter("action", "shorturl");
        pMethod.addParameter("format", "simple");
        pMethod.addParameter("url", url);
        if (keyword != null) {
            pMethod.addParameter("keyword", keyword);
        }

        try {
            int returnCode = client.executeMethod(pMethod);

            if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
                System.err.println("The Post method is not implemented by this URI");
                pMethod.getResponseBodyAsString();
            } else {
                br = new BufferedReader(new InputStreamReader(pMethod.getResponseBodyAsStream()));
                String readLine;
                if (((readLine = br.readLine()) != null)) {
                    result = readLine;
                }
            }
        } catch (Exception e) {
            System.err.println(e);
        } finally {
            pMethod.releaseConnection();
            if (br != null) {
                try {
                    br.close();
                } catch (Exception fe) {
                    fe.printStackTrace();
                }
            }
        }
        return result;
    }
    return null;
}

From source file:cn.newtouch.util.HttpClientUtil.java

/**
 * ?url??post/*from   w ww .  j  a  v a  2  s. c  o  m*/
 * 
 * @param url
 * @param paramsStr
 *            ?
 * @param method
 * @return String ?
 */
public static String post(String url, String paramsStr, String method) {

    HttpClient client = new HttpClient();
    HttpMethod httpMethod = new PostMethod(url);
    httpMethod.setQueryString(paramsStr);
    try {
        int returnCode = client.executeMethod(httpMethod);
        if (returnCode == HttpStatus.SC_OK) {
            return httpMethod.getResponseBodyAsString();
        } else if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
            System.err.println("The Post method is not implemented by this URI");
        }
    } catch (Exception e) {
        System.err.println(e);
    } finally {
        httpMethod.releaseConnection();
    }
    return null;
}

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

/**
 * HTTP GET?HTML//from w w w.j  av  a  2s. c  o m
 * 
 * @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:com.comcast.cats.service.util.HttpClientUtil.java

public static synchronized Object getForObject(String uri, Map<String, String> paramMap) {
    Object responseObject = new Object();

    HttpMethod httpMethod = new GetMethod(uri);

    if ((null != paramMap) && (!paramMap.isEmpty())) {
        httpMethod.setQueryString(getNameValuePair(paramMap));
    }// w  w  w  . ja  v  a2s .c o  m

    Yaml yaml = new Yaml();

    HttpClient client = new HttpClient();
    InputStream responseStream = null;
    Reader inputStreamReader = null;

    try {
        int responseCode = client.executeMethod(httpMethod);

        if (HttpStatus.SC_OK != responseCode) {
            logger.error("[ REQUEST  ] " + httpMethod.getURI().toString());
            logger.error("[ METHOD   ] " + httpMethod.getName());
            logger.error("[ STATUS   ] " + responseCode);
        } else {
            logger.trace("[ REQUEST  ] " + httpMethod.getURI().toString());
            logger.trace("[ METHOD   ] " + httpMethod.getName());
            logger.trace("[ STATUS   ] " + responseCode);
        }

        responseStream = httpMethod.getResponseBodyAsStream();
        inputStreamReader = new InputStreamReader(responseStream, VideoRecorderServiceConstants.UTF);
        responseObject = yaml.load(inputStreamReader);
    } catch (IOException ioException) {
        ioException.printStackTrace();
    } finally {
        cleanUp(inputStreamReader, responseStream, httpMethod);
    }

    return responseObject;
}

From source file:com.comcast.cats.service.util.HttpClientUtil.java

public static synchronized Object postForObject(String uri, Map<String, String> paramMap) {
    Object responseObject = new Object();

    HttpMethod httpMethod = new PostMethod(uri);

    if ((null != paramMap) && (!paramMap.isEmpty())) {
        httpMethod.setQueryString(getNameValuePair(paramMap));
    }// w  ww  . ja va 2s  .  co  m

    Yaml yaml = new Yaml();

    HttpClient client = new HttpClient();
    InputStream responseStream = null;
    Reader inputStreamReader = null;

    try {
        int responseCode = client.executeMethod(httpMethod);

        if (HttpStatus.SC_OK != responseCode) {
            logger.error("[ REQUEST  ] " + httpMethod.getURI().toString());
            logger.error("[ METHOD   ] " + httpMethod.getName());
            logger.error("[ STATUS   ] " + responseCode);
        } else {
            logger.trace("[ REQUEST  ] " + httpMethod.getURI().toString());
            logger.trace("[ METHOD   ] " + httpMethod.getName());
            logger.trace("[ STATUS   ] " + responseCode);
        }

        responseStream = httpMethod.getResponseBodyAsStream();
        inputStreamReader = new InputStreamReader(responseStream, VideoRecorderServiceConstants.UTF);
        responseObject = yaml.load(inputStreamReader);
    } catch (IOException ioException) {
        ioException.printStackTrace();
    } finally {
        cleanUp(inputStreamReader, responseStream, httpMethod);
    }

    return responseObject;
}

From source file:com.comcast.cats.service.util.HttpClientUtil.java

public static synchronized Object deleteForObject(String uri, Map<String, String> paramMap) {
    Object responseObject = new Object();

    HttpMethod httpMethod = new DeleteMethod(uri);

    if ((null != paramMap) && (!paramMap.isEmpty())) {
        httpMethod.setQueryString(getNameValuePair(paramMap));
    }//w  ww .j av a  2s . c o m

    Yaml yaml = new Yaml();

    HttpClient client = new HttpClient();
    InputStream responseStream = null;
    Reader inputStreamReader = null;

    try {
        int responseCode = client.executeMethod(httpMethod);

        if (HttpStatus.SC_OK != responseCode) {
            logger.error("[ REQUEST  ] " + httpMethod.getURI().toString());
            logger.error("[ METHOD   ] " + httpMethod.getName());
            logger.error("[ STATUS   ] " + responseCode);
        } else {
            logger.trace("[ REQUEST  ] " + httpMethod.getURI().toString());
            logger.trace("[ METHOD   ] " + httpMethod.getName());
            logger.trace("[ STATUS   ] " + responseCode);
        }

        responseStream = httpMethod.getResponseBodyAsStream();
        inputStreamReader = new InputStreamReader(responseStream, VideoRecorderServiceConstants.UTF);
        responseObject = yaml.load(inputStreamReader);
    } catch (IOException ioException) {
        ioException.printStackTrace();
    } finally {
        cleanUp(inputStreamReader, responseStream, httpMethod);
    }

    return responseObject;
}

From source file:lucee.commons.net.http.httpclient3.HttpMethodCloner.java

/**
* Clones a HttpMethod. &ltbr>// w ww.j  a  va2 s .c om
* &ltb&gtAttention:</b> You have to clone a method before it has
* been executed, because the URI can change if followRedirects
* is set to true.
*
* @param m the HttpMethod to clone
*
* @return the cloned HttpMethod, null if the HttpMethod could
* not be instantiated
*
* @throws java.io.IOException if the request body couldn't be read
*/
public static HttpMethod clone(HttpMethod m) {
    HttpMethod copy = null;
    try {
        copy = m.getClass().newInstance();
    } catch (InstantiationException iEx) {
    } catch (IllegalAccessException iaEx) {
    }
    if (copy == null) {
        return null;
    }
    copy.setDoAuthentication(m.getDoAuthentication());
    copy.setFollowRedirects(m.getFollowRedirects());
    copy.setPath(m.getPath());
    copy.setQueryString(m.getQueryString());

    Header[] h = m.getRequestHeaders();
    int size = (h == null) ? 0 : h.length;

    for (int i = 0; i < size; i++) {
        copy.setRequestHeader(new Header(h[i].getName(), h[i].getValue()));
    }
    copy.setStrictMode(m.isStrictMode());
    if (m instanceof HttpMethodBase) {
        copyHttpMethodBase((HttpMethodBase) m, (HttpMethodBase) copy);
    }
    if (m instanceof EntityEnclosingMethod) {
        copyEntityEnclosingMethod((EntityEnclosingMethod) m, (EntityEnclosingMethod) copy);
    }
    return copy;
}

From source file:lucee.commons.net.http.httpclient3.HTTPEngine3Impl.java

/**
 * FUNKTIONIERT NICHT, HOST WIRD NICHT UEBERNOMMEN
 * Clones a http method and sets a new url
 * @param src/*from w  ww .  j  a va2s .  c  o  m*/
 * @param url
 * @return
 */
private static HttpMethod clone(HttpMethod src, URL url) {
    HttpMethod trg = HttpMethodCloner.clone(src);
    HostConfiguration trgConfig = trg.getHostConfiguration();
    trgConfig.setHost(url.getHost(), url.getPort(), url.getProtocol());
    trg.setPath(url.getPath());
    trg.setQueryString(url.getQuery());

    return trg;
}