Example usage for org.apache.commons.httpclient.methods GetMethod setQueryString

List of usage examples for org.apache.commons.httpclient.methods GetMethod setQueryString

Introduction

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

Prototype

public void setQueryString(String queryString) 

Source Link

Usage

From source file:org.openo.nfvo.monitor.dac.util.APIHttpClient.java

public static String doGet(String url, String queryString, String charset, String token) {
    HttpClient httpClient = new HttpClient();
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
    GetMethod getMethod = new GetMethod(url);
    if (!Global.isEmpty(queryString)) {
        getMethod.setQueryString(queryString);
    }//from  w  w w  .  j  a va 2 s .c om
    getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 10000);

    if (!Global.isEmpty(token)) {
        getMethod.addRequestHeader("X-Auth-Token", token);
    }
    getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
    String response = "";
    try {
        int statusCode = httpClient.executeMethod(getMethod);
        if (statusCode != HttpStatus.SC_OK) {
            logger.error("request error: " + getMethod.getStatusLine());
        }
        byte[] responseBody = getMethod.getResponseBody();
        response = new String(responseBody, charset);
        logger.debug("----------response:" + response);
    } catch (HttpException e) {
        logger.error("Exception", e);
    } catch (IOException e) {
        logger.error("Exception", e);
    } finally {
        getMethod.releaseConnection();
    }
    return response;
}

From source file:org.openo.nfvo.monitor.umc.util.APIHttpClient.java

public static String doGet(String url, String queryString, String charset, String token) {
    HttpClient httpClient = new HttpClient();
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
    GetMethod getMethod = new GetMethod(url);
    if (!Global.isEmpty(queryString)) {
        getMethod.setQueryString(queryString);
    }/*from   w ww.  java2 s. c  om*/
    getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 10000);

    if (!Global.isEmpty(token)) {
        getMethod.addRequestHeader("X-Auth-Token", token);
    }
    getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
    String response = "";
    try {
        int statusCode = httpClient.executeMethod(getMethod);
        if (statusCode != HttpStatus.SC_OK) {
            logger.error("request error: " + getMethod.getStatusLine());
        } else {
            byte[] responseBody = getMethod.getResponseBody();
            response = new String(responseBody, charset);
            logger.debug("----------response:" + response);
        }

    } catch (HttpException e) {
        logger.error("Exception", e);
    } catch (IOException e) {
        logger.error("Exception", e);
    } finally {
        getMethod.releaseConnection();
    }
    return response;
}

From source file:org.openrdf.http.client.HTTPClient.java

public void getStatements(Resource subj, URI pred, Value obj, boolean includeInferred, RDFHandler handler,
        Resource... contexts) throws IOException, RDFHandlerException, RepositoryException,
        UnauthorizedException, QueryInterruptedException {
    checkRepositoryURL();/*www.j  a  v  a2  s . co m*/

    GetMethod method = new GetMethod(Protocol.getStatementsLocation(getRepositoryURL()));
    setDoAuthentication(method);

    List<NameValuePair> params = new ArrayList<NameValuePair>(5);
    if (subj != null) {
        params.add(new NameValuePair(Protocol.SUBJECT_PARAM_NAME, Protocol.encodeValue(subj)));
    }
    if (pred != null) {
        params.add(new NameValuePair(Protocol.PREDICATE_PARAM_NAME, Protocol.encodeValue(pred)));
    }
    if (obj != null) {
        params.add(new NameValuePair(Protocol.OBJECT_PARAM_NAME, Protocol.encodeValue(obj)));
    }
    for (String encodedContext : Protocol.encodeContexts(contexts)) {
        params.add(new NameValuePair(Protocol.CONTEXT_PARAM_NAME, encodedContext));
    }
    params.add(new NameValuePair(Protocol.INCLUDE_INFERRED_PARAM_NAME, Boolean.toString(includeInferred)));

    method.setQueryString(params.toArray(new NameValuePair[params.size()]));

    try {
        getRDF(method, handler, true);
    } catch (MalformedQueryException e) {
        logger.warn("Server reported unexpected malfored query error", e);
        throw new RepositoryException(e.getMessage(), e);
    } finally {
        releaseConnection(method);
    }
}

From source file:org.ozsoft.xmldb.exist.ExistConnector.java

@Override
public String callModule(String uri, Map<String, String> params) throws XmldbException {
    // Use the REST interface for executing XQuery modules.
    String actualUri = String.format("%s/rest%s", existUri, uri);
    GetMethod getMethod = new GetMethod(actualUri);
    if (params != null && params.size() > 0) {
        NameValuePair[] nameValuePairs = new NameValuePair[params.size()];
        int i = 0;
        for (Entry<String, String> param : params.entrySet()) {
            nameValuePairs[i++] = new NameValuePair(param.getKey(), param.getValue());
        }/*from w  w  w.  ja v a 2  s .c  o m*/
        getMethod.setQueryString(nameValuePairs);
    }
    String result = null;
    try {
        // Execute query.
        int statusCode = httpClient.executeMethod(getMethod);
        if (statusCode >= STATUS_ERROR) {
            if (statusCode == NOT_FOUND) {
                throw new NotFoundException(uri);
            } else if (statusCode == AUTHORIZATION_REQUIRED || statusCode == NOT_AUTHORIZED) {
                throw new NotAuthorizedException(String.format("Not authorized to execute module '%s'", uri));
            } else {
                throw new XmldbException(String
                        .format("Could not retrieve resource '%s' (HTTP status code: %d)", uri, statusCode));
            }
        }

        // Read response body.
        Reader reader = new InputStreamReader(getMethod.getResponseBodyAsStream());
        StringBuilder sb2 = new StringBuilder();
        char[] buffer = new char[BUFFER_SIZE];
        int read = 0;
        while ((read = reader.read(buffer)) > 0) {
            sb2.append(buffer, 0, read);
        }
        reader.close();
        result = sb2.toString();
        LOG.trace("Query result:\n" + result);
    } catch (IOException e) {
        String msg = String.format("Error executing XQuery module '%s'", uri);
        throw new XmldbException(msg, e);
    }
    return result;
}

From source file:org.pentaho.mantle.server.DebugMantleServlet.java

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // use HTTPClient to forward on the data to whatever server we want
    // eg. http://localhost:8080/pentaho/MantleService
    // 1. set the contentType
    // 2. add the data
    // 3. tack the response onto our response
    try {//  w w w  .j a v a  2 s  .c o  m
        HttpClient client = new HttpClient();
        GetMethod getMethod = null;

        String passthru = req.getParameter("passthru"); //$NON-NLS-1$

        if (!"".equals(passthru)) { //$NON-NLS-1$
            getMethod = new GetMethod("http://localhost:8080/pentaho/" + passthru); //$NON-NLS-1$
            getMethod.setQueryString(req.getQueryString());
        } else {
            // not known
            resp.setStatus(404);
            return;
        }

        // If server userid/password was supplied, use basic authentication to
        // authenticate with the server.
        Credentials creds = new UsernamePasswordCredentials("joe", "password"); //$NON-NLS-1$ //$NON-NLS-2$
        client.getState().setCredentials(AuthScope.ANY, creds);
        client.getParams().setAuthenticationPreemptive(true);

        try {
            @SuppressWarnings("unused")
            int status = client.executeMethod(getMethod);
            String postResult = getMethod.getResponseBodyAsString();
            resp.getOutputStream().write(postResult.getBytes("UTF-8")); //$NON-NLS-1$
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
    }

}

From source file:org.pentaho.pac.server.common.ThreadSafeHttpClient.java

private static void setGetMethodParams(GetMethod method, Map<String, Object> mapParams) {
    NameValuePair[] params = mapToNameValuePair(mapParams);
    method.setQueryString(params);
}

From source file:org.pentaho.platform.dataaccess.client.ConnectionServiceClient.java

/**
 * Deletes a connection from the server's configuration.
 * Returns true if the attempt was successful.
 * setHost(), setUserId() and setPassword() must be called before this
 * method is called.//from  w  w  w.j  a  v  a  2s.c o m
 * @param connectionName The name of the connection to be deleted
 * @return True if the deletion was successful
 */
public boolean deleteConnection(String connectionName) throws ConnectionServiceException {
    GetMethod callMethod = new GetMethod(serviceUrl + "/deleteConnectionByName"); //$NON-NLS-1$
    callMethod.setQueryString("name=" + connectionName); //$NON-NLS-1$

    // get the result and parse de-serialize it
    Node node = getResultNode(callMethod);
    return node != null && Boolean.parseBoolean(this.getNodeText(node));
}

From source file:org.rhq.enterprise.server.legacy.rss.DownloadPatchTest.java

private int accessDownload(String username, String password, String softwareId) throws Exception {
    GetMethod method = new GetMethod(URL);
    method.addRequestHeader("username", username);
    method.addRequestHeader("password", password);
    method.setFollowRedirects(true);/*from  w w  w .  j  a  v  a  2s.c o  m*/

    NameValuePair softwarePair = new NameValuePair("softwareId", softwareId);
    method.setQueryString(new NameValuePair[] { softwarePair });

    try {
        int statusCode = client.executeMethod(method);
        log.debug("Method status: " + method.getStatusLine());
        if (HttpStatus.SC_OK == statusCode) {
            String content = readContent(method);
            log.debug("file length: " + content.length());
        }

        return statusCode;
    } catch (Exception e) {
        log.error(e.toString());
        throw e;
    } finally {
        method.releaseConnection();
    }
}

From source file:org.rhq.enterprise.server.legacy.rss.DownloadPatchTest.java

private int accessDownloadGetFileSize(String username, String password, String softwareId) throws Exception {
    GetMethod method = new GetMethod(URL);
    method.addRequestHeader("username", username);
    method.addRequestHeader("password", password);
    method.setFollowRedirects(true);//ww w .j  a  va  2 s.  c o m

    NameValuePair softwarePair = new NameValuePair("softwareId", softwareId);
    method.setQueryString(new NameValuePair[] { softwarePair });

    try {
        int contentLength = 0;
        int statusCode = client.executeMethod(method);
        log.debug("Method status: " + method.getStatusLine());
        if (HttpStatus.SC_OK == statusCode) {
            String content = readContent(method);
            contentLength = content.length();
        }

        return contentLength;
    } catch (Exception e) {
        log.error(e.toString());
        throw e;
    } finally {
        method.releaseConnection();
    }
}

From source file:org.sakaiproject.entitybroker.util.http.HttpRESTUtils.java

/**
 * Fire off a request to a URL using the specified method but reuse the client for efficiency,
 * include optional params and data in the request,
 * the response data will be returned in the object if the request can be carried out
 * //  www.  j av a2s.  com
 * @param httpClientWrapper (optional) allows the http client to be reused for efficiency,
 * if null a new one will be created each time, use {@link #makeReusableHttpClient(boolean, int)} to
 * create a reusable instance
 * @param URL the url to send the request to (absolute or relative, can include query params)
 * @param method the method to use (e.g. GET, POST, etc.)
 * @param params (optional) params to send along with the request, will be encoded in the query string or in the body depending on the method
 * @param params (optional) headers to send along with the request, will be encoded in the headers
 * @param data (optional) data to send along in the body of the request, this only works for POST and PUT requests, ignored for the other types
 * @param guaranteeSSL if this is true then the request is sent in a mode which will allow self signed certs to work,
 * otherwise https requests will fail if the certs cannot be centrally verified
 * @return an object representing the response, includes data about the response
 * @throws HttpRequestException if the request cannot be processed for some reason (this is unrecoverable)
 */
@SuppressWarnings("deprecation")
public static HttpResponse fireRequest(HttpClientWrapper httpClientWrapper, String URL, Method method,
        Map<String, String> params, Map<String, String> headers, Object data, boolean guaranteeSSL) {
    if (guaranteeSSL) {
        // added this to attempt to force the SSL self signed certs to work
        Protocol myhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
        Protocol.registerProtocol("https", myhttps);
    }

    if (httpClientWrapper == null || httpClientWrapper.getHttpClient() == null) {
        httpClientWrapper = makeReusableHttpClient(false, 0, null);
    }

    HttpMethod httpMethod = null;
    if (method.equals(Method.GET)) {
        GetMethod gm = new GetMethod(URL);
        // put params into query string
        gm.setQueryString(mergeQueryStringWithParams(gm.getQueryString(), params));
        // warn about data being set
        if (data != null) {
            System.out.println(
                    "WARN: data cannot be passed in GET requests, data will be ignored (org.sakaiproject.entitybroker.util.http.HttpUtils#fireRequest)");
        }
        gm.setFollowRedirects(true);
        httpMethod = gm;
    } else if (method.equals(Method.POST)) {
        PostMethod pm = new PostMethod(URL);
        // special handling for post params
        if (params != null) {
            for (Entry<String, String> entry : params.entrySet()) {
                if (entry.getKey() == null || entry.getValue() == null) {
                    System.out.println("WARN: null value supplied for param name (" + entry.getKey()
                            + ") or value (" + entry.getValue()
                            + ") (org.sakaiproject.entitybroker.util.http.HttpUtils#fireRequest)");
                }
                pm.addParameter(entry.getKey(), entry.getValue());
            }
        }
        // handle data
        handleRequestData(pm, data);
        httpMethod = pm;
    } else if (method.equals(Method.PUT)) {
        PutMethod pm = new PutMethod(URL);
        // put params into query string
        pm.setQueryString(mergeQueryStringWithParams(pm.getQueryString(), params));
        // handle data
        handleRequestData(pm, data);
        httpMethod = pm;
    } else if (method.equals(Method.DELETE)) {
        DeleteMethod dm = new DeleteMethod(URL);
        // put params into query string
        dm.setQueryString(mergeQueryStringWithParams(dm.getQueryString(), params));
        // warn about data being set
        if (data != null) {
            System.out.println(
                    "WARN: data cannot be passed in DELETE requests, data will be ignored (org.sakaiproject.entitybroker.util.http.HttpUtils#fireRequest)");
        }
        httpMethod = dm;
    } else {
        throw new IllegalArgumentException("Cannot handle method: " + method);
    }
    // set the headers for the request
    if (headers != null) {
        for (Entry<String, String> entry : headers.entrySet()) {
            httpMethod.addRequestHeader(entry.getKey(), entry.getValue());
        }
    }

    HttpResponse response = null;
    try {
        int responseCode = httpClientWrapper.getHttpClient().executeMethod(httpMethod);
        response = new HttpResponse(responseCode);

        // Avoid DOS because of large responses using up all memory in the system - https://jira.sakaiproject.org/browse/SAK-20405
        InputStream is = httpMethod.getResponseBodyAsStream();
        StringBuffer out = new StringBuffer();
        byte[] b = new byte[4096];
        for (int n; (n = is.read(b)) != -1;) {
            out.append(new String(b, 0, n));
            if (out.length() > MAX_RESPONSE_SIZE_CHARS) {
                // die if the response exceeds the maximum chars allowed
                throw new HttpRequestException("Response size (" + out.length() + " chars) from url (" + URL
                        + ") exceeded the maximum allowed batch response size (" + MAX_RESPONSE_SIZE_CHARS
                        + " chars) while processing the response");
            }
        }
        String body = out.toString();

        //String body = httpMethod.getResponseBodyAsString();
        //         byte[] responseBody = httpMethod.getResponseBody();
        //         if (responseBody != null) {
        //            body = new String(responseBody, "UTF-8");
        //         }
        response.setResponseBody(body);
        response.setResponseMessage(httpMethod.getStatusText());
        // now get the headers
        HashMap<String, String[]> responseHeaders = new HashMap<String, String[]>();
        Header[] respHeaders = httpMethod.getResponseHeaders();
        for (int i = 0; i < respHeaders.length; i++) {
            Header header = respHeaders[i];
            // now we convert the headers from these odd pairs into something more like servlets expect
            HeaderElement[] elements = header.getElements();
            if (elements == null || elements.length == 0) {
                continue;
            } else if (elements.length >= 1) {
                String[] values = new String[elements.length];
                StringBuilder sb = new StringBuilder();
                for (int j = 0; j < elements.length; j++) {
                    sb.setLength(0); // clear the StringBuilder
                    sb.append(elements[j].getName());
                    if (elements[j].getValue() != null) {
                        sb.append("=");
                        sb.append(elements[j].getValue());
                    }
                    values[j] = sb.toString();
                }
                responseHeaders.put(header.getName(), values);
            }
        }
        response.setResponseHeaders(responseHeaders);
    } catch (HttpException he) {
        // error contained in he.getMessage()
        throw new HttpRequestException(
                "Fatal HTTP Request Error: " + "Could not sucessfully fire request to url (" + URL
                        + ") using method (" + method + ")  :: " + he.getMessage(),
                he);
    } catch (IOException ioe) {
        // other exception
        throw new HttpIOException(
                "IOException (transport/connection) Error: " + "Could not sucessfully fire request to url ("
                        + URL + ") using method (" + method + ")  :: " + ioe.getMessage(),
                ioe);
    } finally {
        httpMethod.releaseConnection();
    }
    return response;
}