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:edu.unc.lib.dl.ui.service.XMLRetrievalService.java

public static Document getXMLDocument(String url) throws HttpException, IOException, JDOMException {
    SAXBuilder builder = new SAXBuilder();

    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    method.getParams().setParameter("http.socket.timeout", new Integer(2000));
    method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    method.getParams().setParameter("http.useragent", "");

    InputStream responseStream = null;
    Document document = null;// w  w  w. j av  a  2s . c  o m

    try {
        client.executeMethod(method);
        responseStream = method.getResponseBodyAsStream();
        document = builder.build(responseStream);
    } finally {
        if (responseStream != null)
            responseStream.close();
        method.releaseConnection();
    }

    return document;
}

From source file:fr.matriciel.AnnotationClient.java

public static String request(HttpMethod method) throws AnnotationException {

    String response = null;// ww w  .jav  a2s  . co m

    // 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) {
            System.out.println("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) {
        throw new AnnotationException("Protocol error executing HTTP request.", e);
    } catch (IOException e) {
        throw new AnnotationException("Transport error executing HTTP request.", e);
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return response;

}

From source file:com.ms.commons.utilities.HttpClientUtils.java

/**
 * <pre>/*from   ww  w .  j  av a 2  s. co m*/
 * 
 * 
 * try {
 *      inputStream = getResponseBodyAsStream(method, tryTimes, soTimeoutMill);
 * } finally {
 *      IOUtils.closeQuietly(inputStream);
 *      method.releaseConnection();
 * }
 * 
 * @param method
 * @param tryTimes
 * @param soTimeoutMill
 * @return
 */
public static InputStream getResponseBodyAsStream(HttpMethod method, Integer tryTimes, Integer soTimeoutMill) {
    init();
    if (tryTimes == null) {
        tryTimes = 1;
    }
    if (soTimeoutMill == null) {
        soTimeoutMill = 20000;
    }
    method.getParams().setSoTimeout(soTimeoutMill);
    for (int i = 0; i < tryTimes; i++) {
        try {
            int responseCode = client.executeMethod(method);
            if (responseCode == HttpStatus.SC_OK || responseCode == HttpStatus.SC_MOVED_PERMANENTLY
                    || responseCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                return method.getResponseBodyAsStream();
            }
            logger.error(String.format(
                    "getResponseBodyAsString failed, responseCode: %s, should be 200, 301, 302", responseCode));
        } catch (Exception e) {
            logger.error("getResponseBodyAsString failed", e);
        } finally {
            // method releaseConnection  ResponseStream ResponseStream
            // ?finally { method.releaseConnection }
            // method.releaseConnection();
        }
    }
    return null;
}

From source file:com.feilong.tools.net.httpclient3.HttpClientUtil.java

/**
 * Gets the http method.//from w  w w .j  a  v a2  s  . co m
 * 
 * @param httpClientConfig
 *            the http client config
 * @return the http method
 * @throws HttpClientException
 *             the http client util exception
 */
private static HttpMethod getHttpMethod(HttpClientConfig httpClientConfig) throws HttpClientException {
    if (log.isDebugEnabled()) {
        log.debug("[httpClientConfig]:{}", JsonUtil.format(httpClientConfig));
    }

    HttpMethod httpMethod = setUriAndParams(httpClientConfig);
    HttpMethodParams httpMethodParams = httpMethod.getParams();
    // TODO
    httpMethodParams.setParameter(HttpMethodParams.USER_AGENT, DEFAULT_USER_AGENT);

    // ????
    httpMethodParams.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
    return httpMethod;
}

From source file:edu.utah.further.core.ws.HttpUtil.java

/**
 * @param url/*www  . ja va2  s  . c  o  m*/
 * @return
 */
private static HttpMethod newGetMethod(final String url) {
    final HttpMethod method = new GetMethod(url);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(NUMBER_HTTP_REQUEST_TRIALS, false));
    return method;
}

From source file:com.ms.commons.utilities.HttpClientUtils.java

public static String getResponseBodyAsString(HttpMethod method, Integer tryTimes, String responseCharSet,
        Integer maximumResponseByteSize, Integer soTimeoutMill) {
    init();/*from  w ww.  java 2  s  .  c o  m*/
    if (tryTimes == null) {
        tryTimes = 1;
    }
    if (StringUtils.isBlank(responseCharSet)) {
        responseCharSet = "utf-8";
    }
    if (maximumResponseByteSize == null) {
        maximumResponseByteSize = 50 * 1024 * 1024;
    }
    if (soTimeoutMill == null) {
        soTimeoutMill = 20000;
    }
    method.getParams().setSoTimeout(soTimeoutMill);
    InputStream httpInputStream = null;
    for (int i = 0; i < tryTimes; i++) {
        try {
            int responseCode = client.executeMethod(method);
            if (responseCode == HttpStatus.SC_OK || responseCode == HttpStatus.SC_MOVED_PERMANENTLY
                    || responseCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                if (method instanceof HttpMethodBase) {
                    responseCharSet = ((HttpMethodBase) method).getResponseCharSet();
                }
                int read = 0;
                byte[] cbuf = new byte[4096];
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                httpInputStream = method.getResponseBodyAsStream();
                while ((read = httpInputStream.read(cbuf)) >= 0) {
                    baos.write(cbuf, 0, read);
                    if (baos.size() >= maximumResponseByteSize) {
                        break;
                    }
                }
                String content = baos.toString(responseCharSet);
                return content;
            }
            logger.error(String.format(
                    "getResponseBodyAsString failed, responseCode: %s, should be 200, 301, 302", responseCode));
            return "";
        } catch (Exception e) {
            logger.error("getResponseBodyAsString failed", e);
        } finally {
            IOUtils.closeQuietly(httpInputStream);
            method.releaseConnection();
        }
    }
    return "";
}

From source file:edu.utah.further.core.ws.HttpUtil.java

/**
 * Open an HTTP GET method connection to a URL and read the returned response into an
 * object.// ww w .  j  ava2  s.  c o  m
 * 
 * @param url
 *            remote URL (usually a web service's URL)
 * @param httpMethod
 *            HTTP method
 * @return <code>HttpClient</code> {@link HttpMethod} transfer object, containing the
 *         response headers and body
 */
public static HttpResponseTo getHttpResponse(final String url, final HttpMethod method) {
    if (log.isDebugEnabled()) {
        log.debug("Sending HTTP " + method + " request to " + url);
    }

    // Create an instance of HttpClient.
    final HttpClient client = new HttpClient();

    // Create a method instance.
    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(NUMBER_HTTP_REQUEST_TRIALS, false));
    try {
        // Execute the method
        final int statusCode = client.executeMethod(method);
        if (statusCode >= 400) {
            log.error("Method failed: " + method.getStatusLine());
        }
        return new HttpResponseTo(method);
    } catch (final Throwable e) {
        if (log.isInfoEnabled()) {
            log.info("Failed to receive HTTP request from " + url + ": " + e.getMessage());
        }
    }
    return null;
}

From source file:com.cordys.coe.ac.httpconnector.execution.MethodExecutor.java

/**
 * Send the HTTP request to the web server and returns the response.
 * //ww w. j  av a2s .c  o  m
 * @param reqNode
 *            Request XML node.
 * @param serverConnection
 *            Server connection information.
 * @param methodInfo
 *            Method information information.
 * @param counters
 *            JMX performance counters
 * @return Response XML node.
 * @throws ConnectorException
 * @throws HandlerException
 */
public static int sendRequest(int reqNode, IServerConnection serverConnection, IMethodConfiguration methodInfo,
        PerformanceCounters counters) throws ConnectorException, HandlerException {
    boolean setJMXInfo = counters == null ? false : true;
    // Get request and response handlers for converting the data.
    IRequestHandler requestHandler = methodInfo.getRequestHandler();
    IResponseHandler responseHandler = methodInfo.getResponseHandler();

    // Create the connection
    HttpClient client = serverConnection.getHttpClient();

    client.getParams().setContentCharset("UTF-8");
    client.getParams().setCredentialCharset("UTF-8");
    client.getParams().setHttpElementCharset("UTF-8");

    HttpMethod httpMethod;
    int timeout = serverConnection.getTimeout();

    // Convert the SOAP request XML into an HTTP request.
    long startTime = 0;
    if (setJMXInfo) {
        startTime = counters.getStartTime();
    }
    httpMethod = requestHandler.process(reqNode, serverConnection, client);
    if (setJMXInfo) {
        counters.finishRequestTransformation(startTime);
    }

    // Set additional HTTP parameters.
    HttpMethodParams hmpMethodParams = httpMethod.getParams();

    if (hmpMethodParams != null) {
        // Set the authentication character set to UTF-8, if not set.
        String sCredCharset = hmpMethodParams.getCredentialCharset();

        if ((sCredCharset == null) || (sCredCharset.length() == 0)) {
            hmpMethodParams.setCredentialCharset("UTF-8");
        }

        if (timeout > 0) {
            hmpMethodParams.setSoTimeout(timeout);
        }
    }

    // Send the request and handle the response.
    try {
        if (setJMXInfo) {
            startTime = counters.getStartTime();
        }
        int statusCode = client.executeMethod(httpMethod);
        if (setJMXInfo) {
            counters.finishHTTP(startTime);
        }
        int validStatusCode = methodInfo.getValidResponseCode();

        if (statusCode != HttpStatus.SC_OK) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Received HTTP error code: " + statusCode);
            }
        }

        if (setJMXInfo) {
            startTime = counters.getStartTime();
        }
        // Convert the response into XML.
        int responseNode = responseHandler.convertResponseToXml(httpMethod, serverConnection,
                Node.getDocument(reqNode));
        if (setJMXInfo) {
            counters.finishResponseTransformation(startTime);
        }
        if ((validStatusCode >= 0) && (statusCode != validStatusCode)) {
            if (responseNode != 0) {
                Node.delete(responseNode);
                responseNode = 0;
            }

            throw new ConnectorException(ConnectorExceptionMessages.INVALID_STATUS_CODE_RECEIVED_0_EXPECTED_1,
                    statusCode, validStatusCode);
        }

        return responseNode;
    } catch (ConnectorException e) {
        throw e;
    } catch (HttpException e) {
        throw new ConnectorException(e, ConnectorExceptionMessages.HTTP_REQUEST_FAILED_0, e.getMessage());
    } catch (IOException e) {
        throw new ConnectorException(e, ConnectorExceptionMessages.HTTP_CONNECTION_FAILED_0, e.getMessage());
    } catch (XMLException e) {
        throw new ConnectorException((Throwable) e, ConnectorExceptionMessages.INVALID_RESPONSE_XML_RECEIVED);
    } finally {
        // Release the connection.
        httpMethod.releaseConnection();
    }
}

From source file:edu.du.penrose.systems.fedoraProxy.web.bus.ProxyController.java

public static void setDefaultHeaders(HttpMethod method) {

    method.setRequestHeader("Accept",
            "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
    method.setRequestHeader("Connection", "keep-alive");
    method.setRequestHeader("Accept-Encoding", "gzip,deflate,sdch");
    method.setRequestHeader("Accept-Language", "en-US,en;q=0.8");
    method.setRequestHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
    method.setRequestHeader("Cache-Control", "max-age=0");

    method.getParams().setCookiePolicy(CookiePolicy.RFC_2109);

    // response.setCharacterEncoding( "gzip,deflate" );
    // response.setHeader( "Accept-Charset",
    // "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
    // response.setHeader( "Accept-Language", "en-us,en;q=0.5" );

}

From source file:CertStreamCallback.java

private static void invokeActions(String url, String params, byte[] data, Part[] parts, String accept,
        String contentType, String sessionID, String language, String method, Callback callback) {

    if (params != null && !"".equals(params)) {
        if (url.contains("?")) {
            url = url + "&" + params;
        } else {//from w  w  w .jav a  2  s .c o  m
            url = url + "?" + params;
        }
    }

    if (language != null && !"".equals(language)) {
        if (url.contains("?")) {
            url = url + "&language=" + language;
        } else {
            url = url + "?language=" + language;
        }
    }

    HttpMethod httpMethod = null;

    try {
        HttpClient httpClient = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true));
        httpMethod = getHttpMethod(url, method);
        if ((httpMethod instanceof PostMethod) || (httpMethod instanceof PutMethod)) {
            if (null != data)
                ((EntityEnclosingMethod) httpMethod).setRequestEntity(new ByteArrayRequestEntity(data));
            if (httpMethod instanceof PostMethod && null != parts)
                ((PostMethod) httpMethod)
                        .setRequestEntity(new MultipartRequestEntity(parts, httpMethod.getParams()));
        }

        if (sessionID != null) {
            httpMethod.addRequestHeader("Cookie", "JSESSIONID=" + sessionID);
        }

        if (!(httpMethod instanceof PostMethod && null != parts)) {
            if (null != accept && !"".equals(accept))
                httpMethod.addRequestHeader("Accept", accept);
            if (null != contentType && !"".equals(contentType))
                httpMethod.addRequestHeader("Content-Type", contentType);
        }

        int statusCode = httpClient.executeMethod(httpMethod);
        if (statusCode != HttpStatus.SC_OK) {
            throw ActionException.create(ClientMessages.CON_ERROR1, httpMethod.getStatusLine());
        }

        contentType = null != httpMethod.getResponseHeader("Content-Type")
                ? httpMethod.getResponseHeader("Content-Type").getValue()
                : accept;

        InputStream o = httpMethod.getResponseBodyAsStream();
        if (callback != null) {
            callback.execute(o, contentType, sessionID);
        }

    } catch (Exception e) {
        String result = BizClientUtils.doError(e, contentType);
        ByteArrayInputStream in = null;
        try {
            in = new ByteArrayInputStream(result.getBytes("UTF-8"));
            if (callback != null) {
                callback.execute(in, contentType, null);
            }

        } catch (UnsupportedEncodingException e1) {
            throw new RuntimeException(e1.getMessage() + "", e1);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                }
            }
        }
    } finally {
        // 
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
}