Example usage for org.apache.commons.httpclient.params HttpMethodParams RETRY_HANDLER

List of usage examples for org.apache.commons.httpclient.params HttpMethodParams RETRY_HANDLER

Introduction

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

Prototype

String RETRY_HANDLER

To view the source code for org.apache.commons.httpclient.params HttpMethodParams RETRY_HANDLER.

Click Source Link

Usage

From source file:jp.go.nict.langrid.servicesupervisor.invocationprocessor.executor.ServiceInvoker.java

/**
 * /* w w  w. j a v  a2  s.c  om*/
 * 
 */
public static int invoke(URL url, String userName, String password, Map<String, String> headers,
        InputStream input, HttpServletResponse output, OutputStream errorOut, int connectionTimeout,
        int soTimeout) throws IOException, SocketTimeoutException {
    HttpClient client = HttpClientUtil.createHttpClientWithHostConfig(url);
    SimpleHttpConnectionManager manager = new SimpleHttpConnectionManager(true);
    manager.getParams().setConnectionTimeout(connectionTimeout);
    manager.getParams().setSoTimeout(soTimeout);
    manager.getParams().setMaxConnectionsPerHost(client.getHostConfiguration(), 2);
    client.setHttpConnectionManager(manager);
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(0, false));

    PostMethod method = new PostMethod(url.getFile());
    method.setRequestEntity(new InputStreamRequestEntity(input));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        method.addRequestHeader(e.getKey(), e.getValue());
    }
    if (!headers.containsKey("Content-Type"))
        method.addRequestHeader("Content-Type", "text/xml; charset=utf-8");
    if (!headers.containsKey("Accept"))
        method.addRequestHeader("Accept", "application/soap+xml, application/dime, multipart/related, text/*");
    if (!headers.containsKey("SOAPAction"))
        method.addRequestHeader("SOAPAction", "\"\"");
    if (!headers.containsKey("User-Agent"))
        method.addRequestHeader("User-Agent", "Langrid Service Invoker/1.0");
    if (userName != null) {
        int port = url.getPort();
        if (port == -1) {
            port = url.getDefaultPort();
            if (port == -1) {
                port = 80;
            }
        }
        if (password == null) {
            password = "";
        }
        client.getState().setCredentials(new AuthScope(url.getHost(), port, null),
                new UsernamePasswordCredentials(userName, password));
        client.getParams().setAuthenticationPreemptive(true);
        method.setDoAuthentication(true);
    }

    try {
        int status;
        try {
            status = client.executeMethod(method);
        } catch (SocketTimeoutException e) {
            status = HttpServletResponse.SC_REQUEST_TIMEOUT;
        }
        output.setStatus(status);
        if (status == 200) {
            for (Header h : method.getResponseHeaders()) {
                String name = h.getName();
                if (name.startsWith("X-Langrid") || (!throughHeaders.contains(name.toLowerCase())))
                    continue;
                String value = h.getValue();
                output.addHeader(name, value);
            }
            OutputStream os = output.getOutputStream();
            StreamUtil.transfer(method.getResponseBodyAsStream(), os);
            os.flush();
        } else if (status == HttpServletResponse.SC_REQUEST_TIMEOUT) {
        } else {
            StreamUtil.transfer(method.getResponseBodyAsStream(), errorOut);
        }
        return status;
    } finally {
        manager.shutdown();
    }
}

From source file:io.sightly.tck.http.Client.java

/**
 * Creates a basic HTTP client./*  w  w w  . j  ava 2  s  .co  m*/
 */
public Client() {
    client = new HttpClient();
    client.getHttpConnectionManager().setParams(prepareDefaultClientParameters());
    DefaultHttpMethodRetryHandler retryHandler = new DefaultHttpMethodRetryHandler(3, true);
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler);
}

From source file:com.mythesis.userbehaviouranalysis.AnnotationClient.java

public String request(HttpMethod method) throws AnnotationException {

    String response = null;/*w ww. j av a2  s .c  o  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) {
            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.
        InputStream responseBodyAsStream = method.getResponseBodyAsStream();
        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        StringWriter writer = new StringWriter();
        IOUtils.copy(responseBodyAsStream, writer, "utf-8");
        response = writer.toString();

    } 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.unicauca.braim.http.HttpBraimClient.java

public Token GET_Token(String email_or_username, String password) throws IOException, Exception {
    Token token = null;//from   w w  w  . j  a  v  a2 s .  c  o m
    Gson gson = new Gson();

    String data = "data=" + email_or_username + "&password=" + password;
    GetMethod method = new GetMethod(api_url + "/api/v1/token?" + data);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    int statusCode = client.executeMethod(method);
    if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + method.getStatusLine());
        throw new Exception("The username or password are invalid");
    }

    byte[] responseBody = method.getResponseBody();
    String response = new String(responseBody, "UTF-8");
    token = gson.fromJson(response, Token.class);
    System.out.println("algo");

    return token;
}

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

public void testRestAuthentication() {
    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    // Create a method instance.
    GetMethod method = new GetMethod("http://www.google.com");

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

    try {/*from  w w w. j  a  v  a2  s  .c o m*/
        // Execute the method.
        int statusCode = client.executeMethod(method);

        assertEquals(statusCode, HttpStatus.SC_OK);

        // Read the response body.
        byte[] responseBody = method.getResponseBody();

        assertTrue(responseBody != null && responseBody.length != 0);

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

    } catch (HttpException e) {
        fail("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        fail("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:eu.eco2clouds.accounting.testbedclient.ClientHC.java

/**
 * Connects to an testbed URL to get the XML representations of Host Info
 * And it returns it as a null//w w w.j  a  v a 2s  .co  m
 * @param testbed object representing the testbed from which we want to know the host info
 * @return A XML string with the Host info, if there was any HTTP error, it returns empty String... 
 */
public String getHostInfo(Testbed testbed) {
    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    // Create a method instance.
    GetMethod method = new GetMethod(testbed.getUrl());

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

    String response = "";

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

        if (statusCode != HttpStatus.SC_OK) { //TODO test for this case... 
            logger.warn("Get host information of testbed: " + testbed.getName() + " failed: "
                    + method.getStatusLine());
        } else {
            // Read the response body.
            byte[] responseBody = method.getResponseBody();
            response = new String(responseBody);
        }

    } catch (HttpException e) {
        logger.warn("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        logger.warn("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    return response;
}

From source file:ensen.controler.AnnotationClient.java

public String request(HttpMethod method) throws AnnotationException {

    String response = null;//from   www . j av  a 2 s.  c o m

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

    try {
        // Execute the method.
        client.setHttpConnectionManager(new MultiThreadedHttpConnectionManager());
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            System.out.println("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        InputStream responseBodyStream = method.getResponseBodyAsStream(); //Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.

        int b = responseBodyStream.read();
        ArrayList<Integer> bytes = new ArrayList<Integer>();
        while (b != -1) {
            bytes.add(b);
            b = responseBodyStream.read();
        }
        byte[] responseBody = new byte[bytes.size()];

        for (int i = 0; i < bytes.size(); i++) {
            responseBody[i] = bytes.get(i).byteValue();
        }
        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        response = new String(responseBody);

    } catch (HttpException e) {
        System.out.println("Fatal protocol violation: " + e.getMessage());
        try {
            System.err.println(method.getURI());
        } catch (URIException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        throw new AnnotationException("Protocol error executing HTTP request.", e);
    } catch (IOException e) {
        System.out.println("Fatal transport error: " + e.getMessage());
        System.out.println(method.getQueryString());
        throw new AnnotationException("Transport error executing HTTP request.", e);
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return response;

}

From source file:mesquite.tol.lib.BaseHttpRequestMaker.java

public static boolean contactServer(String s, String URI, StringBuffer response) {
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(URI);
    NameValuePair[] pairs = new NameValuePair[1];
    pairs[0] = new NameValuePair("build",
            StringEscapeUtils.escapeHtml("\t" + s + "\tOS =\t" + System.getProperty("os.name") + "\t"
                    + System.getProperty("os.version") + "\tjava =\t" + System.getProperty("java.version")
                    + "\t" + System.getProperty("java.vendor")));
    method.setQueryString(pairs);/*  w  ww  . jav a  2 s  . com*/

    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    return executeMethod(client, method, response);
}

From source file:ehu.ned.DBpediaSpotlightClient.java

public String request(HttpMethod method) throws AnnotationException {

    String response = null;//from   ww  w  .j  a  va2s.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) {
            LOG.error("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        // // Deal with the response.
        // // Use caution: ensure correct character encoding and is not binary data
        InputStream responseBody = method.getResponseBodyAsStream();
        response = IOUtils.toString(responseBody, "UTF-8");

    } 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.khipu.lib.java.KhipuService.java

protected String post(Map data) throws KhipuJSONException, IOException {

    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(Khipu.API_URL + getMethodEndpoint());
    NameValuePair[] params = new NameValuePair[data.keySet().size()];

    int i = 0;/*w ww . j  av  a 2  s .  c o  m*/
    for (Iterator iterator = data.keySet().iterator(); iterator.hasNext(); i++) {
        String key = (String) iterator.next();
        params[i] = new NameValuePair(key, (String) data.get(key));
    }

    postMethod.setRequestBody(params);

    postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    if (client.executeMethod(postMethod) == HttpStatus.SC_OK) {
        InputStream stream = postMethod.getResponseBodyAsStream();
        String contentAsString = getContentAsString(stream);
        stream.close();
        postMethod.releaseConnection();
        return contentAsString;
    }
    InputStream stream = postMethod.getResponseBodyAsStream();
    String contentAsString = getContentAsString(stream);
    stream.close();
    postMethod.releaseConnection();
    throw new KhipuJSONException(contentAsString);
}