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:org.encuestame.core.util.SocialUtils.java

/**
 * Get TinyUrl./*  ww w . j ava2 s. co  m*/
 * @param url
 * @return
 * @throws HttpException
 * @throws IOException
 */
public static String getYourls(final String url) {
    String yourlsShortUrl = url;
    HttpClientParams params = new HttpClientParams();
    params.setConnectionManagerTimeout(EnMePlaceHolderConfigurer.getIntegerProperty("application.timeout"));
    params.setSoTimeout(EnMePlaceHolderConfigurer.getIntegerProperty("application.timeout"));
    HttpClient httpclient = new HttpClient(params); //TODO: time out??
    HttpMethod method = new GetMethod(EnMePlaceHolderConfigurer.getProperty("short.yourls.path"));
    method.setQueryString(new NameValuePair[] { new NameValuePair("url", url),
            new NameValuePair("action", "shorturl"), new NameValuePair("format", "json"),
            new NameValuePair("signature", EnMePlaceHolderConfigurer.getProperty("short.yourls.key")) });
    System.out.println("method--->" + method.getPath());
    System.out.println("method--->" + method.getQueryString());
    try {
        httpclient.executeMethod(method);
        final Object jsonObject = JSONValue.parse(method.getResponseBodyAsString());
        final JSONObject o = (JSONObject) jsonObject;
        //{"message":"Please log in","errorCode":403}"
        Long errorCode = (Long) o.get("errorCode");
        if (errorCode != null) {
            throw new EnMeException("Yourls error: " + errorCode);
        }
        yourlsShortUrl = (String) o.get("shorturl");
    } catch (HttpException e) {
        log.error("HttpException " + e);
        yourlsShortUrl = url;
    } catch (IOException e) {
        log.error("IOException" + e);
        yourlsShortUrl = url;
    } catch (Exception e) {
        //e.printStackTrace();
        log.error("IOException" + e);
        yourlsShortUrl = url;
    } finally {
        RequestSessionMap.setErrorMessage("short url is not well configured");
        method.releaseConnection();
    }
    return yourlsShortUrl;
}

From source file:org.encuestame.core.util.SocialUtils.java

/**
 * Get TinyUrl.//from  w w w.j  ava2 s .c  o  m
 *
 * @param string
 * @return
 * @throws HttpException
 * @throws IOException
 */
public static String getTinyUrl(String string) {
    String tinyUrl = string;
    HttpClientParams params = new HttpClientParams();
    params.setConnectionManagerTimeout(EnMePlaceHolderConfigurer.getIntegerProperty("application.timeout"));
    params.setSoTimeout(EnMePlaceHolderConfigurer.getIntegerProperty("application.timeout"));
    HttpClient httpclient = new HttpClient(params); //TODO: time out??
    //httpclient.setConnectionTimeout(EnMePlaceHolderConfigurer.getIntegerProperty("application.timeout"));
    log.debug("tiny url timeout " + EnMePlaceHolderConfigurer.getIntegerProperty("application.timeout"));
    //httpclient.setParams(params);
    HttpMethod method = new GetMethod(SocialUtils.TINY_URL);
    method.setQueryString(new NameValuePair[] { new NameValuePair("url", string) });
    try {
        log.debug("tiny url execute: " + string);
        httpclient.executeMethod(method);
        tinyUrl = method.getResponseBodyAsString();
    } catch (HttpException e) {
        log.error("HttpException " + e);
        tinyUrl = string;
    } catch (IOException e) {
        log.error("IOException" + e);
        tinyUrl = string;
    } finally {
        method.releaseConnection();
    }
    return tinyUrl;
}

From source file:org.encuestame.core.util.SocialUtils.java

/**
 * Short URL with bitly.com.//from w  w  w . j  av  a  2  s  . com
 * @param urlPath url
 * @param key bitly key
 * @param login bitly login
 * @return
 */
public static String getBitLy(final String urlPath, final String key, final String login) {
    final HttpClient httpclient = new HttpClient();
    final HttpMethod method = new GetMethod(SocialUtils.BITLY_SHORT_URL);
    method.setQueryString(
            new NameValuePair[] { new NameValuePair("longUrl", urlPath), new NameValuePair("version", "2.0.1"),
                    new NameValuePair("login", login), new NameValuePair("apiKey", key),
                    new NameValuePair("format", "json"), new NameValuePair("history", "1") });
    String responseXml = null;
    try {
        httpclient.executeMethod(method);
        //{"errorCode": 0, "errorMessage": "",
        //"results": {"http://www.encuestame.org": {"userHash": "gmks0X", "shortKeywordUrl": "", "hash": "hMMQuX",
        // "shortCNAMEUrl": "http://bit.ly/gmks0X", "shortUrl": "http://bit.ly/gmks0X"}},
        //"statusCode": "OK"}
        final Object jsonObject = JSONValue.parse(method.getResponseBodyAsString());
        log.debug("getBitLy: " + jsonObject.toString());
        final JSONObject o = (JSONObject) jsonObject;
        final JSONObject results = (JSONObject) o.get("results");
        final JSONObject url = (JSONObject) results.get(urlPath);
        responseXml = (String) url.get("shortUrl");
    } catch (HttpException e1) {
        log.error(e1);
        responseXml = urlPath;
    } catch (IOException e1) {
        log.error(e1);
        responseXml = urlPath;
    } catch (Exception e) {
        log.error(e);
        responseXml = urlPath;
    }
    return responseXml;
}

From source file:org.geotools.data.couchdb.client.CouchDBClient.java

/**
 * //from   w  ww  .  j  a va 2s  . c o  m
 * @param path
 * @param queryParams
 * @return
 * @throws IOException
 */
public CouchDBResponse get(String path, NameValuePair[] queryParams) throws IOException {
    HttpMethod get = new GetMethod(url(path));
    if (queryParams != null) {
        get.setQueryString(queryParams);
    }
    return executeMethod(get);
}

From source file:org.infoglue.cms.applications.managementtool.actions.UploadPortletAction.java

/**
* Report to deliver engines that a portlet has been uploaded
* 
* @param contentId//from   ww w . j a v  a  2s  .  c  om
*            contentId of portlet
*/
private void updateDeliverEngines(Integer digitalAssetId) {
    List allUrls = CmsPropertyHandler.getInternalDeliveryUrls();
    allUrls.addAll(CmsPropertyHandler.getPublicDeliveryUrls());

    Iterator urlIterator = allUrls.iterator();
    while (urlIterator.hasNext()) {
        String url = (String) urlIterator.next() + "/DeployPortlet.action";

        try {
            HttpClient client = new HttpClient();

            // establish a connection within 5 seconds
            client.setConnectionTimeout(5000);

            // set the default credentials
            HttpMethod method = new GetMethod(url);
            method.setQueryString("digitalAssetId=" + digitalAssetId);
            method.setFollowRedirects(true);

            // execute the method
            client.executeMethod(method);
            StatusLine status = method.getStatusLine();
            if (status != null && status.getStatusCode() == 200) {
                log.info("Successfully deployed portlet at " + url);
            } else {
                log.warn("Failed to deploy portlet at " + url + ": " + status);
            }

            //clean up the connection resources
            method.releaseConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     Properties props = CmsPropertyHandler.getProperties();
     for (Enumeration keys = props.keys(); keys.hasMoreElements();) {
    String key = (String) keys.nextElement();
    if (key.startsWith(PORTLET_DEPLOY_PREFIX)) {
        String url = props.getProperty(key);
        try {
            HttpClient client = new HttpClient();
            
            //establish a connection within 5 seconds
            client.setConnectionTimeout(5000);
            
            //set the default credentials
            HttpMethod method = new GetMethod(url);
            method.setQueryString("digitalAssetId=" + digitalAssetId);
            method.setFollowRedirects(true);
            
            //execute the method
            client.executeMethod(method);
            StatusLine status = method.getStatusLine();
            if (status != null && status.getStatusCode() == 200) {
                log.info("Successfully deployed portlet at " + url);
            } else {
                log.warn("Failed to deploy portlet at " + url + ": " + status);
            }
            
            //clean up the connection resources
            method.releaseConnection();
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
        }
    }
     }
     */

}

From source file:org.infoscoop.request.OAuth2Authenticator.java

public void doAuthentication(HttpClient client, ProxyRequest request, HttpMethod method, String uid, String pwd)
        throws ProxyAuthenticationException {
    ProxyRequest.OAuth2Config oauthConfig = request.getOauth2Config();
    try {//from   w ww .  j av  a  2 s .co m
        OAuthConsumer consumer = newConsumer(oauthConfig.serviceName, oauthConfig, getCallbackURL(request));
        if (oauthConfig.accessToken == null) {
            returnApprovalUrl(request, consumer);
        }

        if (oauthConfig.validityPeriodUTC != null) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(new Date());
            if (cal.getTimeInMillis() > oauthConfig.validityPeriodUTC) {
                if (oauthConfig.refreshToken == null) {
                    OAuthService.getHandle().deleteOAuth2Token(request.getPortalUid(), oauthConfig.gadgetUrl,
                            oauthConfig.serviceName);
                    returnApprovalUrl(request, consumer);
                } else {
                    log.error(
                            "AccessToken was expired, try re-get the token. [" + oauthConfig.serviceName + "]");
                    getAccessTokenByRefreshToken(request, consumer);
                    OAuth2Token token2 = OAuth2TokenDAO.newInstance().getAccessToken(request.getPortalUid(),
                            oauthConfig.gadgetUrl, oauthConfig.serviceName);
                    oauthConfig.setAccessToken(token2.getAccessToken());
                    oauthConfig.setRefreshToken(token2.getRefreshToken());
                    oauthConfig.setValidityPeriodUTC(token2.getValidityPeriodUTC());
                }
            }
        }

        Map<String, String> parameters = null;
        String contentType = request.getRequestHeader("Content-Type");
        if (contentType != null && contentType.startsWith("application/x-www-form-urlencoded")
                && method.getName().equals("POST")) {
            // TODO analyze charset
            String charset = RequestUtil.getCharset(contentType);
            parameters = RequestUtil.parseRequestBody(request.getRequestBody(), charset);
        }

        if ("Bearer".equalsIgnoreCase(oauthConfig.tokenType)) {
            method.addRequestHeader("Authorization", oauthConfig.tokenType + " " + oauthConfig.accessToken);
        } else {
            method.addRequestHeader("Authorization", "OAuth " + oauthConfig.accessToken);

            String queryString = method.getQueryString();
            queryString = "access_token=" + oauthConfig.accessToken + "&" + queryString;
            method.setQueryString(queryString);
        }
    } catch (URISyntaxException e) {
        throw new ProxyAuthenticationException(e);
    } catch (OAuthException e) {
        throw new ProxyAuthenticationException(e);
    } catch (IOException e) {
        throw new ProxyAuthenticationException(e);
    }
}

From source file:org.infoscoop.request.SignedAuthenticator.java

public void doAuthentication(HttpClient client, ProxyRequest request, HttpMethod method, String uid, String pwd)
        throws ProxyAuthenticationException {
    try {// w  ww  . ja  v  a 2s . c o  m
        OAuthConsumer consumer = newConsumer();
        OAuthAccessor accessor = new OAuthAccessor(consumer);

        Map<String, String> optionParams = new HashMap<String, String>(request.getFilterParameters());

        String targetUrlPath = analyzeUrl(request.getTargetURL(), optionParams);

        String userId = SecurityController.getPrincipalByType("UIDPrincipal").getName();
        optionParams.put("opensocial_viewer_id", userId);
        optionParams.put("opensocial_owner_id", userId);
        optionParams.put("opensocial_app_url", request.getRequestHeader("gadgetUrl"));
        optionParams.put("opensocial_app_id", request.getRequestHeader("moduleId"));
        optionParams.put("opensocial_instance_id", request.getRequestHeader("moduleId"));
        optionParams.put("xoauth_signature_publickey", PUBLIC_KEY_NAME);
        optionParams.put("xoauth_public_key", PUBLIC_KEY_NAME);

        Map<String, String> postParams = new HashMap<String, String>();
        String contentType = request.getRequestHeader("Content-Type");
        if (contentType != null && contentType.startsWith("application/x-www-form-urlencoded")
                && method.getName().equalsIgnoreCase("POST")) {

            String charset = RequestUtil.getCharset(contentType);
            postParams = RequestUtil.parseRequestBody(request.getRequestBody(), charset);
            optionParams.putAll(postParams);
        }

        OAuthMessage message = new OAuthMessage(method.getName(), targetUrlPath, optionParams.entrySet());
        message.addRequiredParameters(accessor);
        List<Map.Entry<String, String>> authParams = message.getParameters();
        List<NameValuePair> queryParams = buildQueryParams(authParams, postParams);
        method.setQueryString((NameValuePair[]) queryParams.toArray(new NameValuePair[0]));

    } catch (Exception e) {
        throw new ProxyAuthenticationException(e);
    }
}

From source file:org.jboss.web.loadbalancer.Loadbalancer.java

protected HttpMethod addRequestData(HttpServletRequest request, HttpMethod method) {
    // add GET-data to query string
    if (request.getQueryString() != null) {
        method.setQueryString(request.getQueryString());
    }//from  www.  ja  v  a 2s  .  com

    // add POST-data to the request
    if (method instanceof PostMethod) {
        PostMethod postMethod = (PostMethod) method;

        Enumeration paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String paramName = (String) paramNames.nextElement();
            postMethod.addParameter(paramName, request.getParameter(paramName));
        }
    }

    return method;
}

From source file:org.ktunaxa.referral.server.mvc.ProxyController.java

@SuppressWarnings("unchecked")
@RequestMapping(value = "/proxy")
public final void proxyAjaxCall(@RequestParam(required = true, value = "url") String url,
        HttpServletRequest request, HttpServletResponse response) throws IOException {

    // URL needs to be url decoded
    url = URLDecoder.decode(url, "utf-8");

    HttpClient client = new HttpClient();
    try {/*w  w w .  j a  v  a2s.  co m*/

        HttpMethod method = null;

        // Split this according to the type of request
        if ("GET".equals(request.getMethod())) {

            method = new GetMethod(url);
            NameValuePair[] pairs = new NameValuePair[request.getParameterMap().size()];
            int i = 0;
            for (Object name : request.getParameterMap().keySet()) {
                pairs[i++] = new NameValuePair((String) name, request.getParameter((String) name));
            }
            method.setQueryString(pairs);

        } else if ("POST".equals(request.getMethod())) {

            method = new PostMethod(url);

            // Set any eventual parameters that came with our original
            // request (POST params, for instance)
            Enumeration paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {

                String paramName = (String) paramNames.nextElement();
                ((PostMethod) method).setParameter(paramName, request.getParameter(paramName));
            }

        } else {

            throw new NotImplementedException("This proxy only supports GET and POST methods.");
        }

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

        // Set the content type, as it comes from the server
        Header[] headers = method.getResponseHeaders();
        for (Header header : headers) {

            if (header.getName().equalsIgnoreCase("Content-Type")) {

                response.setContentType(header.getValue());
            }
        }

        // Write the body, flush and close
        response.getOutputStream().write(method.getResponseBody());

    } catch (HttpException e) {

        // log.error("Oops, something went wrong in the HTTP proxy", null, e);
        response.getOutputStream().write(e.toString().getBytes("UTF-8"));
        throw e;

    } catch (IOException e) {

        e.printStackTrace();
        response.getOutputStream().write(e.toString().getBytes("UTF-8"));
        throw e;
    }
}

From source file:org.mule.transport.http.transformers.ObjectToHttpClientMethodRequest.java

protected HttpMethod createGetMethod(MuleMessage msg, String outputEncoding) throws Exception {
    final Object src = msg.getPayload();
    // TODO It makes testing much harder if we use the endpoint on the
    // transformer since we need to create correct message types and endpoints
    // URI uri = getEndpoint().getEndpointURI().getUri();
    final URI uri = getURI(msg);
    HttpMethod httpMethod;
    String query = uri.getRawQuery();

    httpMethod = new GetMethod(uri.toString());
    String paramName = msg.getOutboundProperty(HttpConnector.HTTP_GET_BODY_PARAM_PROPERTY, null);
    if (paramName != null) {
        paramName = URLEncoder.encode(paramName, outputEncoding);

        String paramValue;//from w  w  w.  j  ava2 s  .co  m
        Boolean encode = msg.getInvocationProperty(HttpConnector.HTTP_ENCODE_PARAMVALUE);
        if (encode == null) {
            encode = msg.getOutboundProperty(HttpConnector.HTTP_ENCODE_PARAMVALUE, true);
        }

        if (encode) {
            paramValue = URLEncoder.encode(src.toString(), outputEncoding);
        } else {
            paramValue = src.toString();
        }

        if (!(src instanceof NullPayload) && !StringUtils.EMPTY.equals(src)) {
            if (query == null) {
                query = paramName + "=" + paramValue;
            } else {
                query += "&" + paramName + "=" + paramValue;
            }
        }
    }

    httpMethod.setQueryString(query);
    return httpMethod;
}