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

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

Introduction

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

Prototype

@Override
public void setQueryString(NameValuePair[] params) 

Source Link

Document

Sets the query string of this HTTP method.

Usage

From source file:com.cyberway.issue.crawler.datamodel.credential.HtmlFormCredential.java

public boolean populate(CrawlURI curi, HttpClient http, HttpMethod method, String payload) {
    // http is not used.
    // payload is not used.
    boolean result = false;
    Map formItems = null;/*from  w  w w .ja va 2  s  . c  o  m*/
    try {
        formItems = getFormItems(curi);
    } catch (AttributeNotFoundException e1) {
        logger.severe("Failed get of form items for " + curi);
    }
    if (formItems == null || formItems.size() <= 0) {
        try {
            logger.severe("No form items for " + method.getURI());
        } catch (URIException e) {
            logger.severe("No form items and exception getting uri: " + e.getMessage());
        }
        return result;
    }

    NameValuePair[] data = new NameValuePair[formItems.size()];
    int index = 0;
    String key = null;
    for (Iterator i = formItems.keySet().iterator(); i.hasNext();) {
        key = (String) i.next();
        data[index++] = new NameValuePair(key, (String) formItems.get(key));
    }
    if (method instanceof PostMethod) {
        ((PostMethod) method).setRequestBody(data);
        result = true;
    } else if (method instanceof GetMethod) {
        // Append these values to the query string.
        // Get current query string, then add data, then get it again
        // only this time its our data only... then append.
        HttpMethodBase hmb = (HttpMethodBase) method;
        String currentQuery = hmb.getQueryString();
        hmb.setQueryString(data);
        String newQuery = hmb.getQueryString();
        hmb.setQueryString(((StringUtils.isNotEmpty(currentQuery)) ? currentQuery + "&" : "") + newQuery);
        result = true;
    } else {
        logger.severe("Unknown method type: " + method);
    }
    return result;
}

From source file:jeeves.utils.XmlRequest.java

private HttpMethodBase setupHttpMethod() throws UnsupportedEncodingException {
    HttpMethodBase httpMethod;

    if (method == Method.GET) {
        httpMethod = new GetMethod();

        if (query != null && !query.equals(""))
            httpMethod.setQueryString(query);

        else if (alSimpleParams.size() != 0)
            httpMethod.setQueryString(alSimpleParams.toArray(new NameValuePair[alSimpleParams.size()]));

        httpMethod.addRequestHeader("Accept", !useSOAP ? "application/xml" : "application/soap+xml");
        httpMethod.setFollowRedirects(true);
    } else {/*w  w w .j  a  v  a  2 s .  c o  m*/
        PostMethod post = new PostMethod();

        if (!useSOAP) {
            postData = (postParams == null) ? "" : Xml.getString(new Document(postParams));
            post.setRequestEntity(new StringRequestEntity(postData, "application/xml", "UTF8"));
        } else {
            postData = Xml.getString(new Document(soapEmbed(postParams)));
            post.setRequestEntity(new StringRequestEntity(postData, "application/soap+xml", "UTF8"));
        }

        httpMethod = post;
    }

    httpMethod.setPath(address);
    httpMethod.setDoAuthentication(useAuthent());

    return httpMethod;
}

From source file:fr.openwide.talendalfresco.rest.client.AlfrescoRestClient.java

public void execute(ClientCommand clientCommand) throws RestClientException {

    int statusCode = -1;
    HttpMethodBase method = null;
    try {/*from   w  w w .j  a v a2s .  c o  m*/
        // building method (and body entity if any)
        method = clientCommand.createMethod();

        // setting server URL
        method.setURI(new URI(restCommandUrlPrefix + clientCommand.getName(), false));
        method.getParams().setContentCharset(this.restEncoding);

        // building params (adding ticket)
        List<NameValuePair> params = clientCommand.getParams();
        params.add(new NameValuePair(TICKET_PARAM, ticket));
        method.setQueryString(params.toArray(EMPTY_NAME_VALUE_PAIR));

        // Execute the method.
        statusCode = client.executeMethod(method);

        // checking HTTP status
        if (statusCode != HttpStatus.SC_OK) {
            throw new RestClientException("Bad HTTP Status : " + statusCode);
        }

        // parsing response
        XMLEventReader xmlReader = null;
        try {
            xmlReader = XmlHelper.createXMLEventReader(method.getResponseBodyAsStream(), this.restEncoding);

            clientCommand.handleResponse(xmlReader);

            if (!RestConstants.CODE_OK.equals(clientCommand.getResultCode())) {
                //String msg = "Business error in command " + clientCommand.toString();
                //logger.error(msg, e);
                throw new RestClientException(clientCommand.getResultMessage(),
                        new RestClientException(clientCommand.getResultError()));
            }
        } catch (XMLStreamException e) {
            String msg = "XML parsing error on response body : ";
            try {
                msg += new String(method.getResponseBody());
            } catch (IOException ioex) {
                msg += "[unreadable]";
            }
            ;
            //logger.error(msg, e);
            throw new RestClientException(msg, e);
        } catch (IOException e) {
            String msg = "IO Error when parsing XML response body : ";
            //logger.error(msg, e);
            throw new RestClientException(msg, e);

        } finally {
            if (xmlReader != null) {
                try {
                    xmlReader.close();
                } catch (Throwable t) {
                }
            }
        }

    } catch (RestClientException rcex) {
        throw rcex;
    } catch (URIException e) {
        throw new RestClientException("URI error while executing command " + clientCommand, e);
    } catch (HttpException e) {
        throw new RestClientException("HTTP error while executing command " + clientCommand, e);
    } catch (IOException e) {
        throw new RestClientException("IO error while executing command " + clientCommand, e);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:com.assemblade.client.AbstractClient.java

private void generateSignature(HttpMethodBase method) throws URIException {
    if (authentication != null) {
        String verb = method.getName();
        String url = OAuthEncoder.encode(method.getURI().toString());

        List<NameValuePair> queryStrings = new ArrayList<NameValuePair>();
        queryStrings.add(new NameValuePair(OAuthConstants.CONSUMER_KEY, authentication.getToken()));
        queryStrings.add(new NameValuePair(OAuthConstants.NONCE, timestampService.getNonce()));
        queryStrings.add(new NameValuePair(OAuthConstants.SIGN_METHOD, signatureService.getSignatureMethod()));
        queryStrings.add(new NameValuePair(OAuthConstants.TIMESTAMP, timestampService.getTimestampInSeconds()));
        queryStrings.add(new NameValuePair(OAuthConstants.VERSION, "1.0"));
        method.setQueryString(queryStrings.toArray(new NameValuePair[] {}));

        String queryString = OAuthEncoder.encode(method.getQueryString());

        String baseString = verb + "&" + url + "&" + queryString;

        String signature = signatureService.getSignature(baseString, authentication.getSecret(), "");

        queryStrings.add(new NameValuePair(OAuthConstants.SIGNATURE, signature));
        method.setQueryString(queryStrings.toArray(new NameValuePair[] {}));
    }//  w  ww .j  a va  2  s.  co m
}

From source file:edu.uci.ics.pregelix.example.util.TestExecutor.java

public InputStream executeQuery(String str, OutputFormat fmt, String url,
        List<CompilationUnit.Parameter> params) throws Exception {
    HttpMethodBase method = null;
    if (str.length() + url.length() < MAX_URL_LENGTH) {
        //Use GET for small-ish queries
        method = new GetMethod(url);
        NameValuePair[] parameters = new NameValuePair[params.size() + 1];
        parameters[0] = new NameValuePair("query", str);
        int i = 1;
        for (CompilationUnit.Parameter param : params) {
            parameters[i++] = new NameValuePair(param.getName(), param.getValue());
        }/*  w  w  w.  j  a  v a  2 s . c om*/
        method.setQueryString(parameters);
    } else {
        //Use POST for bigger ones to avoid 413 FULL_HEAD
        // QQQ POST API doesn't allow encoding additional parameters
        method = new PostMethod(url);
        ((PostMethod) method).setRequestEntity(new StringRequestEntity(str));
    }

    //Set accepted output response type
    method.setRequestHeader("Accept", fmt.mimeType());
    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    executeHttpMethod(method);
    return method.getResponseBodyAsStream();
}

From source file:com.nextcloud.android.sso.InputStreamBinder.java

private InputStream processRequest(final NextcloudRequest request) throws UnsupportedOperationException,
        com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException,
        OperationCanceledException, AuthenticatorException, IOException {
    Account account = AccountUtils.getOwnCloudAccountByName(context, request.getAccountName()); // TODO handle case that account is not found!
    if (account == null) {
        throw new IllegalStateException(EXCEPTION_ACCOUNT_NOT_FOUND);
    }/*  www  .java  2  s  .com*/

    // Validate token
    if (!isValid(request)) {
        throw new IllegalStateException(EXCEPTION_INVALID_TOKEN);
    }

    // Validate URL
    if (request.getUrl().length() == 0 || request.getUrl().charAt(0) != PATH_SEPARATOR) {
        throw new IllegalStateException(EXCEPTION_INVALID_REQUEST_URL,
                new IllegalStateException("URL need to start with a /"));
    }

    OwnCloudClientManager ownCloudClientManager = OwnCloudClientManagerFactory.getDefaultSingleton();
    OwnCloudAccount ocAccount = new OwnCloudAccount(account, context);
    OwnCloudClient client = ownCloudClientManager.getClientFor(ocAccount, context);

    String requestUrl = client.getBaseUri() + request.getUrl();
    HttpMethodBase method;

    switch (request.getMethod()) {
    case "GET":
        method = new GetMethod(requestUrl);
        break;

    case "POST":
        method = new PostMethod(requestUrl);
        if (request.getRequestBody() != null) {
            StringRequestEntity requestEntity = new StringRequestEntity(request.getRequestBody(),
                    CONTENT_TYPE_APPLICATION_JSON, CHARSET_UTF8);
            ((PostMethod) method).setRequestEntity(requestEntity);
        }
        break;

    case "PUT":
        method = new PutMethod(requestUrl);
        if (request.getRequestBody() != null) {
            StringRequestEntity requestEntity = new StringRequestEntity(request.getRequestBody(),
                    CONTENT_TYPE_APPLICATION_JSON, CHARSET_UTF8);
            ((PutMethod) method).setRequestEntity(requestEntity);
        }
        break;

    case "DELETE":
        method = new DeleteMethod(requestUrl);
        break;

    default:
        throw new UnsupportedOperationException(EXCEPTION_UNSUPPORTED_METHOD);

    }

    method.setQueryString(convertMapToNVP(request.getParameter()));
    method.addRequestHeader("OCS-APIREQUEST", "true");

    client.setFollowRedirects(request.isFollowRedirects());
    int status = client.executeMethod(method);

    // Check if status code is 2xx --> https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#2xx_Success
    if (status >= HTTP_STATUS_CODE_OK && status < HTTP_STATUS_CODE_MULTIPLE_CHOICES) {
        return method.getResponseBodyAsStream();
    } else {
        throw new IllegalStateException(EXCEPTION_HTTP_REQUEST_FAILED,
                new IllegalStateException(String.valueOf(status)));
    }
}

From source file:com.funambol.json.api.dao.FunambolJSONApiDAO.java

private void addSinceUntil(HttpMethodBase method, long since, long until) {
    List<NameValuePair> queryParameters = new ArrayList<NameValuePair>();
    if (since >= 0)
        queryParameters.add(new NameValuePair("since", "" + since));
    if (until >= 0)
        queryParameters.add(new NameValuePair("until", "" + until));
    if (queryParameters.size() > 0)
        method.setQueryString(queryParameters.toArray(new NameValuePair[] {}));
}

From source file:com.sun.syndication.propono.atom.client.OAuthStrategy.java

public void addAuthentication(HttpClient httpClient, HttpMethodBase method) throws ProponoException {

    if (state != State.ACCESS_TOKEN) {
        throw new ProponoException("ERROR: authentication strategy failed init");
    }/*from   w ww  .j a v  a2s  .  c o m*/

    // add OAuth name/values to request query string

    // wish we didn't have to parse them apart first, ugh
    List originalqlist = null;
    if (method.getQueryString() != null) {
        String qstring = method.getQueryString().trim();
        qstring = qstring.startsWith("?") ? qstring.substring(1) : qstring;
        originalqlist = new ParameterParser().parse(qstring, '&');
    } else {
        originalqlist = new ArrayList();
    }

    // put query string into hashmap form to please OAuth.net classes
    Map params = new HashMap();
    for (Iterator it = originalqlist.iterator(); it.hasNext();) {
        NameValuePair pair = (NameValuePair) it.next();
        params.put(pair.getName(), pair.getValue());
    }

    // add OAuth params to query string
    params.put("xoauth_requestor_id", username);
    params.put("oauth_consumer_key", consumerKey);
    params.put("oauth_signature_method", keyType);
    params.put("oauth_timestamp", Long.toString(timestamp));
    params.put("oauth_nonce", nonce);
    params.put("oauth_token", accessToken);
    params.put("oauth_token_secret", tokenSecret);

    // sign complete URI
    String finalUri = null;
    OAuthServiceProvider provider = new OAuthServiceProvider(reqUrl, authzUrl, accessUrl);
    OAuthConsumer consumer = new OAuthConsumer(null, consumerKey, consumerSecret, provider);
    OAuthAccessor accessor = new OAuthAccessor(consumer);
    accessor.tokenSecret = tokenSecret;
    OAuthMessage message;
    try {
        message = new OAuthMessage(method.getName(), method.getURI().toString(), params.entrySet());
        message.sign(accessor);

        finalUri = OAuth.addParameters(message.URL, message.getParameters());

    } catch (Exception ex) {
        throw new ProponoException("ERROR: OAuth signing request", ex);
    }

    // pull query string off and put it back onto method
    method.setQueryString(finalUri.substring(finalUri.lastIndexOf("?")));
}

From source file:com.rometools.propono.atom.client.OAuthStrategy.java

@Override
public void addAuthentication(final HttpClient httpClient, final HttpMethodBase method)
        throws ProponoException {

    if (state != State.ACCESS_TOKEN) {
        throw new ProponoException("ERROR: authentication strategy failed init");
    }/*from   ww w.java 2  s  . c  o m*/

    // add OAuth name/values to request query string

    // wish we didn't have to parse them apart first, ugh
    List<NameValuePair> originalqlist = null;
    if (method.getQueryString() != null) {
        String qstring = method.getQueryString().trim();
        qstring = qstring.startsWith("?") ? qstring.substring(1) : qstring;
        @SuppressWarnings("unchecked")
        final List<NameValuePair> parameters = new ParameterParser().parse(qstring, '&');
        originalqlist = parameters;
    } else {
        originalqlist = new ArrayList<NameValuePair>();
    }

    // put query string into hashmap form to please OAuth.net classes
    final Map<String, String> params = new HashMap<String, String>();
    for (final Object element : originalqlist) {
        final NameValuePair pair = (NameValuePair) element;
        params.put(pair.getName(), pair.getValue());
    }

    // add OAuth params to query string
    params.put("xoauth_requestor_id", username);
    params.put("oauth_consumer_key", consumerKey);
    params.put("oauth_signature_method", keyType);
    params.put("oauth_timestamp", Long.toString(timestamp));
    params.put("oauth_nonce", nonce);
    params.put("oauth_token", accessToken);
    params.put("oauth_token_secret", tokenSecret);

    // sign complete URI
    String finalUri = null;
    final OAuthServiceProvider provider = new OAuthServiceProvider(reqUrl, authzUrl, accessUrl);
    final OAuthConsumer consumer = new OAuthConsumer(null, consumerKey, consumerSecret, provider);
    final OAuthAccessor accessor = new OAuthAccessor(consumer);
    accessor.tokenSecret = tokenSecret;
    OAuthMessage message;
    try {
        message = new OAuthMessage(method.getName(), method.getURI().toString(), params.entrySet());
        message.sign(accessor);

        finalUri = OAuth.addParameters(message.URL, message.getParameters());

    } catch (final Exception ex) {
        throw new ProponoException("ERROR: OAuth signing request", ex);
    }

    // pull query string off and put it back onto method
    method.setQueryString(finalUri.substring(finalUri.lastIndexOf("?")));
}

From source file:com.progress.codeshare.esbservice.http.HTTPService.java

public void service(final XQServiceContext ctx) throws XQServiceException {

    try {/*  w  w w .j  ava 2s .c o  m*/
        final XQMessageFactory factory = ctx.getMessageFactory();

        final XQParameters params = ctx.getParameters();

        final int messagePart = params.getIntParameter(PARAM_MESSAGE_PART, XQConstants.PARAM_STRING);

        final String method = params.getParameter(PARAM_METHOD, XQConstants.PARAM_STRING);

        final String uri = params.getParameter(PARAM_URI, XQConstants.PARAM_STRING);

        while (ctx.hasNextIncoming()) {
            final XQEnvelope env = ctx.getNextIncoming();

            final XQMessage origMsg = env.getMessage();

            final XQMessage newMsg = factory.createMessage();

            final HttpClient client = new HttpClient();

            final Iterator headerIterator = origMsg.getHeaderNames();

            if (METHOD_DELETE.equals(method)) {
                final HttpMethodBase req = new DeleteMethod(uri);

                /*
                 * Copy all XQ headers and extract HTTP headers and
                 * parameters
                 */
                while (headerIterator.hasNext()) {
                    final String header = (String) headerIterator.next();

                    newMsg.setHeaderValue(header, origMsg.getHeaderValue(header));

                    final Matcher matcher = PATTERN_HEADER.matcher(header);

                    if (matcher.find())
                        req.addRequestHeader(matcher.group(1),
                                (String) origMsg.getHeaderValue(matcher.group()));

                }

                client.executeMethod(req);

                /* Transform all HTTP to XQ headers */
                final Header[] headers = req.getResponseHeaders();

                for (int i = 0; i < headers.length; i++)
                    newMsg.setHeaderValue(PREFIX_HEADER + headers[i].getName(), headers[i].getValue());

                final XQPart newPart = newMsg.createPart();

                newPart.setContentId("Result");

                newPart.setContent(new String(req.getResponseBody()),
                        req.getResponseHeader("Content-Type").getValue());

                newMsg.addPart(newPart);
            } else if (METHOD_GET.equals(method)) {
                final HttpMethodBase req = new GetMethod();

                final List paramList = new ArrayList();

                /*
                 * Copy all XQ headers and extract HTTP headers and
                 * parameters
                 */
                while (headerIterator.hasNext()) {
                    final String header = (String) headerIterator.next();

                    newMsg.setHeaderValue(header, origMsg.getHeaderValue(header));

                    final Matcher headerMatcher = PATTERN_HEADER.matcher(header);

                    if (headerMatcher.find()) {
                        req.addRequestHeader(headerMatcher.group(1),
                                (String) origMsg.getHeaderValue(headerMatcher.group()));

                        continue;
                    }

                    final Matcher paramMatcher = PATTERN_PARAM.matcher(header);

                    if (paramMatcher.find())
                        paramList.add(new NameValuePair(paramMatcher.group(1),
                                (String) origMsg.getHeaderValue(paramMatcher.group())));

                }

                req.setQueryString((NameValuePair[]) paramList.toArray(new NameValuePair[] {}));

                client.executeMethod(req);

                /* Transform all HTTP to XQ headers */
                final Header[] headers = req.getResponseHeaders();

                for (int i = 0; i < headers.length; i++)
                    newMsg.setHeaderValue(PREFIX_HEADER + headers[i].getName(), headers[i].getValue());

                final XQPart newPart = newMsg.createPart();

                newPart.setContentId("Result");

                newPart.setContent(new String(req.getResponseBody()),
                        req.getResponseHeader("Content-Type").getValue());

                newMsg.addPart(newPart);
            } else if (METHOD_POST.equals(method)) {
                final PostMethod req = new PostMethod(uri);

                /*
                 * Copy all XQ headers and extract HTTP headers and
                 * parameters
                 */
                while (headerIterator.hasNext()) {
                    final String header = (String) headerIterator.next();

                    newMsg.setHeaderValue(header, origMsg.getHeaderValue(header));

                    final Matcher headerMatcher = PATTERN_HEADER.matcher(header);

                    if (headerMatcher.find()) {
                        req.addRequestHeader(headerMatcher.group(1),
                                (String) origMsg.getHeaderValue(headerMatcher.group()));

                        continue;
                    }

                    final Matcher paramMatcher = PATTERN_PARAM.matcher(header);

                    if (paramMatcher.find())
                        req.addParameter(new NameValuePair(paramMatcher.group(1),
                                (String) origMsg.getHeaderValue(paramMatcher.group())));

                }

                final XQPart origPart = origMsg.getPart(messagePart);

                req.setRequestEntity(new StringRequestEntity((String) origPart.getContent(),
                        origPart.getContentType(), null));

                client.executeMethod(req);

                /* Transform all HTTP to XQ headers */
                final Header[] headers = req.getResponseHeaders();

                for (int i = 0; i < headers.length; i++)
                    newMsg.setHeaderValue(PREFIX_HEADER + headers[i].getName(), headers[i].getValue());

                final XQPart newPart = newMsg.createPart();

                newPart.setContentId("Result");

                newPart.setContent(new String(req.getResponseBody()),
                        req.getResponseHeader("Content-Type").getValue());

                newMsg.addPart(newPart);
            } else if (METHOD_PUT.equals(method)) {
                final EntityEnclosingMethod req = new PutMethod(uri);

                /* Copy all XQ headers and extract HTTP headers */
                while (headerIterator.hasNext()) {
                    final String header = (String) headerIterator.next();

                    newMsg.setHeaderValue(header, origMsg.getHeaderValue(header));

                    final Matcher matcher = PATTERN_HEADER.matcher(header);

                    if (matcher.find())
                        req.addRequestHeader(matcher.group(1),
                                (String) origMsg.getHeaderValue(matcher.group()));

                }

                final XQPart origPart = origMsg.getPart(messagePart);

                req.setRequestEntity(new StringRequestEntity((String) origPart.getContent(),
                        origPart.getContentType(), null));

                client.executeMethod(req);

                /* Transform all HTTP to XQ headers */
                final Header[] headers = req.getResponseHeaders();

                for (int i = 0; i < headers.length; i++)
                    newMsg.setHeaderValue(PREFIX_HEADER + headers[i].getName(), headers[i].getValue());

                final XQPart newPart = newMsg.createPart();

                newPart.setContentId("Result");

                newPart.setContent(new String(req.getResponseBody()),
                        req.getResponseHeader("Content-Type").getValue());

                newMsg.addPart(newPart);
            }

            env.setMessage(newMsg);

            final Iterator addressIterator = env.getAddresses();

            if (addressIterator.hasNext())
                ctx.addOutgoing(env);

        }

    } catch (final Exception e) {
        throw new XQServiceException(e);
    }

}