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

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

Introduction

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

Prototype

public abstract HttpMethodParams getParams();

Source Link

Usage

From source file:fr.cls.atoll.motu.library.cas.HttpClientCAS.java

public static String debugHttpMethod(HttpMethod method) {
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append("\nName:");
    stringBuffer.append(method.getName());
    stringBuffer.append("\n");
    stringBuffer.append("\nPath:");
    stringBuffer.append(method.getPath());
    stringBuffer.append("\n");
    stringBuffer.append("\nQueryString:");
    stringBuffer.append(method.getQueryString());
    stringBuffer.append("\n");
    stringBuffer.append("\nUri:");
    try {/*from ww w .  j a va 2s  .  co  m*/
        stringBuffer.append(method.getURI().toString());
    } catch (URIException e) {
        // Do nothing
    }
    stringBuffer.append("\n");
    HttpMethodParams httpMethodParams = method.getParams();
    stringBuffer.append("\nHttpMethodParams:");
    stringBuffer.append(httpMethodParams.toString());

    return stringBuffer.toString();

}

From source file:com.eviware.soapui.impl.wsdl.submit.filters.HttpAuthenticationRequestFilter.java

public static void initRequestCredentials(SubmitContext context, String username, Settings settings,
        String password, String domain) {
    HttpClient httpClient = (HttpClient) context.getProperty(BaseHttpRequestTransport.HTTP_CLIENT);
    HttpMethod httpMethod = (HttpMethod) context.getProperty(BaseHttpRequestTransport.HTTP_METHOD);

    if (StringUtils.isNullOrEmpty(username) && StringUtils.isNullOrEmpty(password)) {
        httpClient.getParams().setAuthenticationPreemptive(false);
        httpMethod.setDoAuthentication(false);
    } else {/*from   w w w  .  j  ava 2 s  . co  m*/
        // set preemptive authentication
        if (settings.getBoolean(HttpSettings.AUTHENTICATE_PREEMPTIVELY)) {
            httpClient.getParams().setAuthenticationPreemptive(true);
            HttpState state = (HttpState) context.getProperty(SubmitContext.HTTP_STATE_PROPERTY);

            if (state != null) {
                Credentials defaultcreds = new UsernamePasswordCredentials(username,
                        password == null ? "" : password);
                state.setCredentials(AuthScope.ANY, defaultcreds);
            }
        } else {
            httpClient.getParams().setAuthenticationPreemptive(false);
        }

        httpMethod.getParams().setParameter(CredentialsProvider.PROVIDER,
                new UPDCredentialsProvider(username, password, domain));

        httpMethod.setDoAuthentication(true);
    }
}

From source file:net.sourceforge.jcctray.model.CCNet.java

protected HttpMethod httpMethod(DashBoardProject project) {
    HttpMethod method = new PostMethod(forceBuildURL(project));
    configureMethod(method, project);/*  ww  w  . j  a  v a  2 s .c  o  m*/
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    return method;
}

From source file:com.intellij.plugins.firstspirit.languagesupport.FirstSpiritClassPathHack.java

public void addFirstSpiritClientJar(UrlClassLoader classLoader, HttpScheme schema, String serverName, int port,
        String firstSpiritUserName, String firstSpiritUserPassword) throws Exception {
    System.out.println("starting to download fs-client.jar");

    String resolvalbleAddress = null;

    // asking DNS for IP Address, if some error occur choose the given value from user
    try {//from w ww.ja  v  a  2s.co m
        InetAddress address = InetAddress.getByName(serverName);
        resolvalbleAddress = address.getHostAddress();
        System.out.println("Resolved address: " + resolvalbleAddress);
    } catch (Exception e) {
        System.err.println("DNS cannot resolve address, using your given value: " + serverName);
        resolvalbleAddress = serverName;
    }

    String uri = schema + "://" + resolvalbleAddress + ":" + port + "/clientjar/fs-client.jar";
    String versionUri = schema + "://" + resolvalbleAddress + ":" + port + "/version.txt";
    String tempDirectory = System.getProperty("java.io.tmpdir");

    System.out.println(uri);
    System.out.println(versionUri);

    HttpClient client = new HttpClient();
    HttpMethod getVersion = new GetMethod(versionUri);
    client.executeMethod(getVersion);
    String currentServerVersionString = getVersion.getResponseBodyAsString();
    System.out
            .println("FirstSpirit server you want to connect to is at version: " + currentServerVersionString);

    File fsClientJar = new File(tempDirectory, "fs-client-" + currentServerVersionString + ".jar");

    if (!fsClientJar.exists()) {
        // get an authentication cookie from FirstSpirit
        HttpMethod post = new PostMethod(uri);
        post.setQueryString("login.user=" + URLEncoder.encode(firstSpiritUserName, "UTF-8") + "&login.password="
                + URLEncoder.encode(firstSpiritUserPassword, "UTF-8") + "&login=webnonsso");
        client.executeMethod(post);
        String setCookieJsession = post.getResponseHeader("Set-Cookie").getValue();

        // download the fs-client.jar by using the authentication cookie
        HttpMethod get = new GetMethod(uri);
        get.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
        get.setRequestHeader("Cookie", setCookieJsession);
        client.executeMethod(get);

        InputStream inputStream = get.getResponseBodyAsStream();
        FileOutputStream outputStream = new FileOutputStream(fsClientJar);
        outputStream.write(IOUtils.readFully(inputStream, -1, false));
        outputStream.close();
        System.out.println("tempfile of fs-client.jar created within path: " + fsClientJar);
    }

    addFile(classLoader, fsClientJar);
}

From source file:com.discogs.api.webservice.impl.HttpClientWebService.java

@Override
public Resp doGet(String url) throws WebServiceException {
    HttpMethod method = new GZipCapableGetMethod(url);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    method.setDoAuthentication(true);//from   w  ww.  ja v  a 2  s .  c o  m

    try {
        // execute the method
        int statusCode = this.httpClient.executeMethod(method);

        if (logger.isDebugEnabled()) {
            logger.debug(method.getResponseBodyAsString());
        }

        switch (statusCode) {
        case HttpStatus.SC_OK:
            return createResp(method.getResponseBodyAsStream());

        case HttpStatus.SC_NOT_FOUND:
            throw new ResourceNotFoundException("Resource not found.", method.getResponseBodyAsString());

        case HttpStatus.SC_BAD_REQUEST:
            throw new RequestException(method.getResponseBodyAsString());

        case HttpStatus.SC_FORBIDDEN:
            throw new AuthorizationException(method.getResponseBodyAsString());

        case HttpStatus.SC_UNAUTHORIZED:
            throw new AuthorizationException(method.getResponseBodyAsString());

        default:
            String em = "web service returned unknown status '" + statusCode + "', response was: "
                    + method.getResponseBodyAsString();
            logger.error(em);
            throw new WebServiceException(em);
        }
    } catch (HttpException e) {
        logger.error("Fatal protocol violation: " + e.getMessage());
        throw new WebServiceException(e.getMessage(), e);
    } catch (IOException e) {
        logger.error("Fatal transport error: " + e.getMessage());
        throw new WebServiceException(e.getMessage(), e);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.npower.dm.msm.tools.PackageCheckerImpl.java

public PackageMetaInfo getPackageMetaInfo(String url) throws DMException {
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    PackageMetaInfo metaInfo = new PackageMetaInfo();
    metaInfo.setUrl(url);//from  w ww  .  j  av a2s .  c om
    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);
        metaInfo.setServerStatus(statusCode);
        if (statusCode != HttpStatus.SC_OK) {
            // System.err.println("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody();
        System.out.println(new String(responseBody));

        Header mimeType = method.getResponseHeader("Content-Type");
        if (mimeType != null) {
            metaInfo.setMimeType(mimeType.getValue());
        }

        Header contentLength = method.getResponseHeader("Content-Length");
        if (contentLength != null && StringUtils.isNotEmpty(contentLength.getValue())) {
            metaInfo.setSize(Integer.parseInt(contentLength.getValue()));
        }

    } catch (HttpException e) {
        metaInfo.setErrorMessage(e.getMessage());
    } catch (IOException e) {
        metaInfo.setErrorMessage(e.getMessage());
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return metaInfo;
}

From source file:net.sourceforge.jcctray.model.HTTPCruise.java

/**
 * Returns a {@link GetMethod} with some configuration set. Clients may
 * override. Calls {@link #configureMethod(HttpMethod, DashBoardProject)} to
 * configure the {@link HttpMethod} for the particular project.
 * /*from w  w w .ja  va 2s  .  c om*/
 * @param project
 *            the project used to configure the {@link HttpMethod}
 * @return a {@link GetMethod}
 */
protected HttpMethod httpMethod(DashBoardProject project) {
    HttpMethod method = new GetMethod(forceBuildURL(project));
    configureMethod(method, project);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    return method;
}

From source file:br.com.edu.dbpediaspotlight.AnnotationClient.java

public String request(HttpMethod method) throws AnnotationException {
    String response = null;/*ww  w  .jav  a2 s.  com*/
    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            LOG.error("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody(); //TODO Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        response = new String(responseBody);

    } catch (HttpException e) {
        LOG.error("Fatal protocol violation: " + e.getMessage());
        throw new AnnotationException("Protocol error executing HTTP request.", e);
    } catch (IOException e) {
        LOG.error("Fatal transport error: " + e.getMessage());
        LOG.error(method.getQueryString());
        throw new AnnotationException("Transport error executing HTTP request.", e);
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return response;

}

From source file:com.panoramagl.downloaders.PLHTTPFileDownloader.java

/**download methods*/

@Override//from   w ww.  j  av  a  2s .  c om
protected byte[] downloadFile() {
    this.setRunning(true);
    byte[] result = null;
    InputStream is = null;
    ByteArrayOutputStream bas = null;
    String url = this.getURL();
    PLFileDownloaderListener listener = this.getListener();
    boolean hasListener = (listener != null);
    int responseCode = -1;
    long startTime = System.currentTimeMillis();
    // HttpClient instance
    HttpClient client = new HttpClient();
    // Method instance
    HttpMethod method = new GetMethod(url);
    // Method parameters
    HttpMethodParams methodParams = method.getParams();
    methodParams.setParameter(HttpMethodParams.USER_AGENT, "PanoramaGL Android");
    methodParams.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
    methodParams.setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(this.getMaxAttempts(), false));
    try {
        // Execute the method
        responseCode = client.executeMethod(method);
        if (responseCode != HttpStatus.SC_OK)
            throw new IOException(method.getStatusText());
        // Get content length
        Header header = method.getRequestHeader("Content-Length");
        long contentLength = (header != null ? Long.parseLong(header.getValue()) : 1);
        if (this.isRunning()) {
            if (hasListener)
                listener.didBeginDownload(url, startTime);
        } else
            throw new PLRequestInvalidatedException(url);
        // Get response body as stream
        is = method.getResponseBodyAsStream();
        bas = new ByteArrayOutputStream();
        byte[] buffer = new byte[256];
        int length = 0, total = 0;
        // Read stream
        while ((length = is.read(buffer)) != -1) {
            if (this.isRunning()) {
                bas.write(buffer, 0, length);
                total += length;
                if (hasListener)
                    listener.didProgressDownload(url, (int) (((float) total / (float) contentLength) * 100.0f));
            } else
                throw new PLRequestInvalidatedException(url);
        }
        if (total == 0)
            throw new IOException("Request data has invalid size (0)");
        // Get data
        if (this.isRunning()) {
            result = bas.toByteArray();
            if (hasListener)
                listener.didEndDownload(url, result, System.currentTimeMillis() - startTime);
        } else
            throw new PLRequestInvalidatedException(url);
    } catch (Throwable e) {
        if (this.isRunning()) {
            PLLog.error("PLHTTPFileDownloader::downloadFile", e);
            if (hasListener)
                listener.didErrorDownload(url, e.toString(), responseCode, result);
        }
    } finally {
        if (bas != null) {
            try {
                bas.close();
            } catch (IOException e) {
                PLLog.error("PLHTTPFileDownloader::downloadFile", e);
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                PLLog.error("PLHTTPFileDownloader::downloadFile", e);
            }
        }
        // Release the connection
        method.releaseConnection();
    }
    this.setRunning(false);
    return result;
}

From source file:fedora.test.integration.TestLargeDatastreams.java

private long exportAPIALite(String dsId) throws Exception {
    String url = apia.describeRepository().getRepositoryBaseURL() + "/get/" + pid + "/" + dsId;
    HttpMethod httpMethod = new GetMethod(url);
    httpMethod.setDoAuthentication(true);
    httpMethod.getParams().setParameter("Connection", "Keep-Alive");

    HttpClient client = fedoraClient.getHttpClient();
    client.executeMethod(httpMethod);//from www . j  a  va 2s  . c o m
    BufferedInputStream dataStream = new BufferedInputStream(httpMethod.getResponseBodyAsStream());

    long bytesRead = 0;
    while (dataStream.read() >= 0) {
        ++bytesRead;
    }

    return bytesRead;
}