Example usage for org.apache.commons.httpclient.params HttpParams setParameter

List of usage examples for org.apache.commons.httpclient.params HttpParams setParameter

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.params HttpParams setParameter.

Prototype

public abstract void setParameter(String paramString, Object paramObject);

Source Link

Usage

From source file:CustomAuthenticationExample.java

public static void main(String[] args) {

    // register the auth scheme
    AuthPolicy.registerAuthScheme(SecretAuthScheme.NAME, SecretAuthScheme.class);

    // include the scheme in the AuthPolicy.AUTH_SCHEME_PRIORITY preference,
    // this can be done on a per-client or per-method basis but we'll do it
    // globally for this example
    HttpParams params = DefaultHttpParams.getDefaultParams();
    ArrayList schemes = new ArrayList();
    schemes.add(SecretAuthScheme.NAME);/*from  ww w  . j av  a2 s  .  co m*/
    schemes.addAll((Collection) params.getParameter(AuthPolicy.AUTH_SCHEME_PRIORITY));
    params.setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, schemes);

    // now that our scheme has been registered we can execute methods against
    // servers that require "Secret" authentication... 
}

From source file:com.cerema.cloud2.lib.resources.status.GetRemoteStatusOperation.java

private boolean tryConnection(OwnCloudClient client) {
    boolean retval = false;
    GetMethod get = null;/* w ww .j av a2 s. com*/
    String baseUrlSt = client.getBaseUri().toString();
    try {
        get = new GetMethod(baseUrlSt + AccountUtils.STATUS_PATH);

        HttpParams params = get.getParams().getDefaultParams();
        params.setParameter(HttpMethodParams.USER_AGENT, OwnCloudClientManagerFactory.getUserAgent());
        get.getParams().setDefaults(params);

        client.setFollowRedirects(false);
        boolean isRedirectToNonSecureConnection = false;
        int status = client.executeMethod(get, TRY_CONNECTION_TIMEOUT, TRY_CONNECTION_TIMEOUT);
        mLatestResult = new RemoteOperationResult((status == HttpStatus.SC_OK), status,
                get.getResponseHeaders());

        String redirectedLocation = mLatestResult.getRedirectedLocation();
        while (redirectedLocation != null && redirectedLocation.length() > 0 && !mLatestResult.isSuccess()) {

            isRedirectToNonSecureConnection |= (baseUrlSt.startsWith("https://")
                    && redirectedLocation.startsWith("http://"));
            get.releaseConnection();
            get = new GetMethod(redirectedLocation);
            status = client.executeMethod(get, TRY_CONNECTION_TIMEOUT, TRY_CONNECTION_TIMEOUT);
            mLatestResult = new RemoteOperationResult((status == HttpStatus.SC_OK), status,
                    get.getResponseHeaders());
            redirectedLocation = mLatestResult.getRedirectedLocation();
        }

        String response = get.getResponseBodyAsString();
        if (status == HttpStatus.SC_OK) {
            JSONObject json = new JSONObject(response);
            if (!json.getBoolean(NODE_INSTALLED)) {
                mLatestResult = new RemoteOperationResult(
                        RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED);
            } else {
                String version = json.getString(NODE_VERSION);
                OwnCloudVersion ocVersion = new OwnCloudVersion(version);
                if (!ocVersion.isVersionValid()) {
                    mLatestResult = new RemoteOperationResult(RemoteOperationResult.ResultCode.BAD_OC_VERSION);

                } else {
                    // success
                    if (isRedirectToNonSecureConnection) {
                        mLatestResult = new RemoteOperationResult(
                                RemoteOperationResult.ResultCode.OK_REDIRECT_TO_NON_SECURE_CONNECTION);
                    } else {
                        mLatestResult = new RemoteOperationResult(
                                baseUrlSt.startsWith("https://") ? RemoteOperationResult.ResultCode.OK_SSL
                                        : RemoteOperationResult.ResultCode.OK_NO_SSL);
                    }

                    ArrayList<Object> data = new ArrayList<Object>();
                    data.add(ocVersion);
                    mLatestResult.setData(data);
                    retval = true;
                }
            }

        } else {
            mLatestResult = new RemoteOperationResult(false, status, get.getResponseHeaders());
        }

    } catch (JSONException e) {
        mLatestResult = new RemoteOperationResult(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED);

    } catch (Exception e) {
        mLatestResult = new RemoteOperationResult(e);

    } finally {
        if (get != null)
            get.releaseConnection();
    }

    if (mLatestResult.isSuccess()) {
        Log_OC.i(TAG, "Connection check at " + baseUrlSt + ": " + mLatestResult.getLogMessage());

    } else if (mLatestResult.getException() != null) {
        Log_OC.e(TAG, "Connection check at " + baseUrlSt + ": " + mLatestResult.getLogMessage(),
                mLatestResult.getException());

    } else {
        Log_OC.e(TAG, "Connection check at " + baseUrlSt + ": " + mLatestResult.getLogMessage());
    }

    return retval;
}

From source file:ir.keloud.android.lib.common.KeloudClient.java

@Override
public int executeMethod(HttpMethod method) throws IOException, HttpException {
    try { // just to log 
        boolean customRedirectionNeeded = false;

        try {/*from  w  w  w .  ja  v a  2  s.  c o  m*/
            method.setFollowRedirects(mFollowRedirects);
        } catch (Exception e) {
            /*
             if (mFollowRedirects) 
               Log_OC.d(TAG, "setFollowRedirects failed for " + method.getName() 
            + " method, custom redirection will be used if needed");
            */
            customRedirectionNeeded = mFollowRedirects;
        }

        // Update User Agent
        HttpParams params = method.getParams();
        String userAgent = KeloudClientManagerFactory.getUserAgent();
        params.setParameter(HttpMethodParams.USER_AGENT, userAgent);

        Log_OC.d(TAG + " #" + mInstanceNumber, "REQUEST " + method.getName() + " " + method.getPath());

        //           logCookiesAtRequest(method.getRequestHeaders(), "before");
        //           logCookiesAtState("before");

        int status = super.executeMethod(method);

        if (customRedirectionNeeded) {
            status = patchRedirection(status, method);
        }

        //           logCookiesAtRequest(method.getRequestHeaders(), "after");
        //           logCookiesAtState("after");
        //           logSetCookiesAtResponse(method.getResponseHeaders());

        return status;

    } catch (IOException e) {
        Log_OC.d(TAG + " #" + mInstanceNumber, "Exception occurred", e);
        throw e;
    }
}

From source file:com.cerema.cloud2.lib.common.OwnCloudClient.java

/**
 * Requests the received method./*from w  w w . j a  va 2  s . c  o  m*/
 *
 * Executes the method through the inherited HttpClient.executedMethod(method).
 *
 * @param method                HTTP method request.
 */
@Override
public int executeMethod(HttpMethod method) throws IOException {
    try {
        // Update User Agent
        HttpParams params = method.getParams();
        String userAgent = OwnCloudClientManagerFactory.getUserAgent();
        params.setParameter(HttpMethodParams.USER_AGENT, userAgent);

        Log_OC.d(TAG + " #" + mInstanceNumber, "REQUEST " + method.getName() + " " + method.getPath());

        //           logCookiesAtRequest(method.getRequestHeaders(), "before");
        //           logCookiesAtState("before");
        method.setFollowRedirects(false);

        int status = super.executeMethod(method);

        if (mFollowRedirects) {
            status = followRedirection(method).getLastStatus();
        }

        //           logCookiesAtRequest(method.getRequestHeaders(), "after");
        //           logCookiesAtState("after");
        //           logSetCookiesAtResponse(method.getResponseHeaders());

        return status;

    } catch (IOException e) {
        //Log_OC.d(TAG + " #" + mInstanceNumber, "Exception occurred", e);
        throw e;
    }
}

From source file:org.apache.jmeter.protocol.http.sampler.HttpClientDefaultParameters.java

/**
 * Loads a property file and converts parameters as necessary.
 * /*from w ww . j  av  a2  s.com*/
 * @param file the file to load
 * @param params Commons HttpClient parameter instance
 * @deprecated HC3.1 will be dropped in upcoming version
 */
@Deprecated
public static void load(String file, final org.apache.commons.httpclient.params.HttpParams params) {
    load(file, new GenericHttpParams() {
        @Override
        public void setParameter(String name, Object value) {
            params.setParameter(name, value);
        }

        @Override
        public void setVersion(String name, String value) throws Exception {
            params.setParameter(name, org.apache.commons.httpclient.HttpVersion.parse("HTTP/" + value));
        }
    });
}

From source file:org.codelabor.system.remoting.http.services.HttpAdapterServiceImpl.java

public String requestByGetMethod(Map<String, String> parameterMap) throws Exception {
    String responseBody = null;/* w  w  w . j  a v  a2 s .co  m*/
    GetMethod method = null;

    try {
        StringBuilder sb = new StringBuilder();
        sb.append(url);
        if (url.indexOf("?") == -1) {
            sb.append("?");
        }
        Set<String> keySet = parameterMap.keySet();
        Iterator<String> iter = keySet.iterator();
        String parameterKey = null;
        while (iter.hasNext()) {
            parameterKey = iter.next();
            sb.append(parameterKey);
            sb.append("=");
            sb.append(parameterMap.get(parameterKey));
            if (iter.hasNext()) {
                sb.append("&");
            }
        }

        String encodedURI = URIUtil.encodeQuery(sb.toString());
        logger.debug("encodedURI: {}", encodedURI);

        method = new GetMethod(encodedURI);
        HttpParams httpParams = new DefaultHttpParams();
        DefaultHttpMethodRetryHandler retryHandler = new DefaultHttpMethodRetryHandler(retry, false);
        httpParams.setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler);
        HttpClient httpClient = new HttpClient(new HttpClientParams(httpParams));

        int statusCode = httpClient.executeMethod(method);
        logger.debug("statusCode: {}", statusCode);
        switch (statusCode) {
        case HttpStatus.SC_OK:
            responseBody = method.getResponseBodyAsString();
            logger.debug("responseBody: {}", responseBody);
            break;
        }
    } catch (Exception e) {
        if (logger.isErrorEnabled()) {
            String messageKey = "error.http.request";
            String userMessage = messageSource.getMessage(messageKey, new String[] {}, "default message",
                    Locale.getDefault());
            logger.error(userMessage, e);
        }
        e.printStackTrace();
        throw e;
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
    return responseBody;
}

From source file:org.codelabor.system.services.HttpAdapterServiceImpl.java

public String request(Map<String, String> parameterMap) {
    StringBuilder stringBuilder = new StringBuilder();
    String responseBody = null;// ww w  . j a  v a2 s . c o  m
    GetMethod method = null;

    try {
        stringBuilder.append(url);
        if (url.indexOf("?") == -1) {
            stringBuilder.append("?");
        }
        Set<String> keySet = parameterMap.keySet();
        Iterator<String> iter = keySet.iterator();
        String parameterKey = null;
        while (iter.hasNext()) {
            parameterKey = iter.next();
            stringBuilder.append(parameterKey);
            stringBuilder.append("=");
            stringBuilder.append(parameterMap.get(parameterKey));
            if (iter.hasNext()) {
                stringBuilder.append("&");
            }
        }

        String encodedURI = URIUtil.encodeQuery(stringBuilder.toString());

        if (log.isDebugEnabled()) {
            log.debug(encodedURI);
        }

        method = new GetMethod(encodedURI);
        HttpParams httpParams = new DefaultHttpParams();
        DefaultHttpMethodRetryHandler retryHandler = new DefaultHttpMethodRetryHandler(retry, false);
        httpParams.setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler);
        HttpClient httpClient = new HttpClient(new HttpClientParams(httpParams));

        int statusCode = httpClient.executeMethod(method);
        if (log.isDebugEnabled()) {
            stringBuilder = new StringBuilder();
            stringBuilder.append("statusCode: ").append(statusCode);
            log.debug(stringBuilder.toString());
        }
        switch (statusCode) {
        case HttpStatus.SC_OK:
            responseBody = method.getResponseBodyAsString();
            break;
        }
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            String messageKey = "error.http.request";
            String userMessage = messageSource.getMessage(messageKey, new String[] {}, "default message",
                    Locale.getDefault());
            log.error(userMessage, e);
        }
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
    return responseBody;
}

From source file:org.jppf.example.webcrawler.JPPFHttpDefaultParamsFactory.java

/**
 * Get the default set of parameters.//w  w  w  . ja v a 2 s. c  o  m
 * @return an <code>HttpParams</code> instance.
 * @see org.apache.commons.httpclient.params.DefaultHttpParamsFactory#getDefaultParams()
 */
@Override
public synchronized HttpParams getDefaultParams() {
    HttpParams params = super.getDefaultParams();
    params.setParameter("http.socket.timeout", Integer.valueOf(socketTimeout));
    params.setParameter("http.method.retry-handler", new JPPFMethodExceptionHandler(maxConnectionRetries));
    return params;
}

From source file:org.kuali.rice.kew.config.ThinClientResourceLoader.java

protected void configureDefaultHttpClientParams(HttpParams params) {
    params.setParameter(HttpClientParams.CONNECTION_MANAGER_CLASS, MultiThreadedHttpConnectionManager.class);
    params.setParameter(HttpMethodParams.COOKIE_POLICY, CookiePolicy.RFC_2109);
    params.setLongParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT,
            new Long(DEFAULT_CONNECTION_MANAGER_TIMEOUT));
    Map<HostConfiguration, Integer> maxHostConnectionsMap = new HashMap<HostConfiguration, Integer>();
    maxHostConnectionsMap.put(HostConfiguration.ANY_HOST_CONFIGURATION, new Integer(DEFAULT_MAX_CONNECTIONS));
    params.setParameter(HttpConnectionManagerParams.MAX_HOST_CONNECTIONS, maxHostConnectionsMap);
    params.setIntParameter(HttpConnectionManagerParams.MAX_TOTAL_CONNECTIONS,
            new Integer(DEFAULT_MAX_CONNECTIONS));
    params.setIntParameter(HttpConnectionManagerParams.CONNECTION_TIMEOUT,
            new Integer(DEFAULT_CONNECTION_TIMEOUT));

    boolean retrySocketException = new Boolean(
            ConfigContext.getCurrentContextConfig().getProperty(RETRY_SOCKET_EXCEPTION_PROPERTY));
    if (retrySocketException) {
        LOG.info("Installing custom HTTP retry handler to retry requests in face of SocketExceptions");
        params.setParameter(HttpMethodParams.RETRY_HANDLER, new CustomHttpMethodRetryHandler());
    }/*from  w w  w.  j a  v a  2  s .  co  m*/
}

From source file:org.kuali.rice.ksb.messaging.HttpClientHelper.java

public static void setParameter(HttpParams params, String paramName, String paramValue) {
    Class<?> paramType = getParameterType(paramName);
    if (paramType.equals(Boolean.class)) {
        params.setBooleanParameter(paramName, Boolean.parseBoolean(paramValue));
    } else if (paramType.equals(Integer.class)) {
        params.setIntParameter(paramName, Integer.parseInt(paramValue));
    } else if (paramType.equals(Long.class)) {
        params.setLongParameter(paramName, Long.parseLong(paramValue));
    } else if (paramType.equals(Double.class)) {
        params.setDoubleParameter(paramName, Double.parseDouble(paramValue));
    } else if (paramType.equals(String.class)) {
        params.setParameter(paramName, paramValue);
    } else if (paramType.equals(Class.class)) {
        try {/*w w w .  j  av  a 2 s .c  o m*/
            Class<?> configuredClass = Class.forName(paramValue, true,
                    ClassLoaderUtils.getDefaultClassLoader());
            params.setParameter(paramName, configuredClass);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("Could not locate the class needed to configure the HttpClient.", e);
        }
    } else {
        throw new RuntimeException("Attempted to configure an HttpClient parameter '" + paramName + "' "
                + "of a type not supported through Workflow configuration: " + paramType.getName());
    }
}