Example usage for org.apache.commons.httpclient DefaultHttpMethodRetryHandler DefaultHttpMethodRetryHandler

List of usage examples for org.apache.commons.httpclient DefaultHttpMethodRetryHandler DefaultHttpMethodRetryHandler

Introduction

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

Prototype

public DefaultHttpMethodRetryHandler(int paramInt, boolean paramBoolean) 

Source Link

Usage

From source file:com.cloudmaster.cmp.util.AlarmSystem.transfer.HttpSender.java

public ResponseObject send(TransportObject object) throws Exception {
    ResponseObject rs = new ResponseObject();
    ByteArrayOutputStream bOs = null;
    DataOutputStream dOs = null;/*from  w w w  .  j  av  a 2s. c o  m*/
    DataInputStream dIs = null;
    HttpClient client;
    PostMethod meth = null;
    byte[] rawData;
    try {
        bOs = new ByteArrayOutputStream();
        dOs = new DataOutputStream(bOs);
        object.toStream(dOs);
        bOs.flush();
        rawData = bOs.toByteArray();

        client = new HttpClient();
        client.setConnectionTimeout(this.timeout);
        client.setTimeout(this.datatimeout);
        client.setHttpConnectionFactoryTimeout(this.timeout);

        meth = new PostMethod(object.getValue(SERVER_URL));
        // meth = new UTF8PostMethod(url);
        meth.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, ENCODING);
        // meth.addParameter(SERVER_ARGS, new String(rawData,"UTF-8"));

        // meth.setRequestBody(new String(rawData));
        // meth.setRequestBody(new String(rawData,"UTF-8"));

        byte[] base64Array = Base64.encode(rawData).getBytes();
        meth.setRequestBody(new String(base64Array));

        // System.out.println(new String(rawData));

        client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(1, false));
        client.executeMethod(meth);

        dIs = new DataInputStream(meth.getResponseBodyAsStream());

        if (meth.getStatusCode() == HttpStatus.SC_OK) {

            Header errHeader = meth.getResponseHeader(HDR_ERROR);

            if (errHeader != null) {
                rs.setError(meth.getResponseBodyAsString());
                return rs;
            }

            rs = ResponseObject.fromStream(dIs);

            return rs;
        } else {
            meth.releaseConnection();
            throw new IOException("Connection failure: " + meth.getStatusLine().toString());
        }
    } finally {
        if (meth != null) {
            meth.releaseConnection();
        }
        if (bOs != null) {
            bOs.close();
        }
        if (dOs != null) {
            dOs.close();
        }
        if (dIs != null) {
            dIs.close();
        }
    }
}

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

public void testRestLogin() {
    // create client and configure it
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);

    // instantiating a new method and configuring it
    GetMethod method = new GetMethod(restCommandUrlPrefix + "login");
    method.setFollowRedirects(true); // ?
    // Provide custom retry handler is necessary (?)
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    NameValuePair[] params = new NameValuePair[] { new NameValuePair("username", "admin"),
            new NameValuePair("password", "admin") };
    method.setQueryString(params);/*from  www  .  j  a  va2  s. co  m*/

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

        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)); // TODO rm

        HashSet<String> defaultElementSet = new HashSet<String>(
                Arrays.asList(new String[] { RestConstants.TAG_COMMAND, RestConstants.TAG_CODE,
                        RestConstants.TAG_CONTENT, RestConstants.TAG_ERROR, RestConstants.TAG_MESSAGE }));
        HashMap<String, String> elementValueMap = new HashMap<String, String>(6);

        try {
            XMLEventReader xmlReader = XmlHelper.getXMLInputFactory()
                    .createXMLEventReader(new ByteArrayInputStream(responseBody));
            StringBuffer singleLevelTextBuf = null;
            while (xmlReader.hasNext()) {
                XMLEvent event = xmlReader.nextEvent();
                switch (event.getEventType()) {
                case XMLEvent.CHARACTERS:
                case XMLEvent.CDATA:
                    if (singleLevelTextBuf != null) {
                        singleLevelTextBuf.append(event.asCharacters().getData());
                    } // else element not meaningful
                    break;
                case XMLEvent.START_ELEMENT:
                    StartElement startElement = event.asStartElement();
                    String elementName = startElement.getName().getLocalPart();
                    if (defaultElementSet.contains(elementName)
                            // TODO another command specific level
                            || "ticket".equals(elementName)) {
                        // reinit buffer at start of meaningful elements
                        singleLevelTextBuf = new StringBuffer();
                    } else {
                        singleLevelTextBuf = null; // not useful
                    }
                    break;
                case XMLEvent.END_ELEMENT:
                    if (singleLevelTextBuf == null) {
                        break; // element not meaningful
                    }

                    // TODO or merely put it in the map since the element has been tested at start
                    EndElement endElement = event.asEndElement();
                    elementName = endElement.getName().getLocalPart();
                    if (defaultElementSet.contains(elementName)) {
                        String value = singleLevelTextBuf.toString();
                        elementValueMap.put(elementName, value);
                        // TODO test if it is code and it is not OK, break to error handling
                    }
                    // TODO another command specific level
                    else if ("ticket".equals(elementName)) {
                        ticket = singleLevelTextBuf.toString();
                    }
                    // singleLevelTextBuf = new StringBuffer(); // no ! in start
                    break;
                }
            }
        } catch (XMLStreamException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Throwable t) {
            // TODO Auto-generated catch block
            t.printStackTrace();
            //throw t;
        }

        String code = elementValueMap.get(RestConstants.TAG_CODE);
        assertTrue(RestConstants.CODE_OK.equals(code));
        System.out.println("got ticket " + ticket);

    } catch (HttpException e) {
        // TODO
        e.printStackTrace();
    } catch (IOException e) {
        // TODO
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:eu.eco2clouds.accounting.bonfire.BFClientAccountingImpl.java

private String getMethod(String url, Boolean exception) {
    // Create an instance of HttpClient.
    HttpClient client = getHttpClient();

    logger.debug("Connecting to: " + url);
    // Create a method instance.
    GetMethod method = new GetMethod(url);
    setHeaders(method);/*  w  w  w  . j a va2  s .  co m*/

    // 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 managed experiments information... : " + url + " 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();
        exception = true;
    } catch (IOException e) {
        logger.warn("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
        exception = true;
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    return response;
}

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

protected HttpMethod httpMethod(DashBoardProject project) {
    HttpMethod method = new PostMethod(forceBuildURL(project));
    configureMethod(method, project);//from  www  .ja  v a 2s  .  co  m
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    return method;
}

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

public static boolean sendInfoToServer(NameValuePair[] pairs, String URI, StringBuffer response) {
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(URI);
    method.setQueryString(pairs);//from   www. j av  a 2s  . c o  m

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

    return executeMethod(client, method, response);
}

From source file:com.tasktop.c2c.server.web.proxy.HttpProxy.java

public HttpProxy() {
    httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
    httpClient.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    httpClient.getHttpConnectionManager().getParams().setSoTimeout(60 * 1000);
    httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(0, false));
}

From source file:br.org.acessobrasil.silvinha.autenticador.AutenticadorConector.java

public boolean autenticarLogin(Login login) {
    boolean autenticado = false;
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(url);
    NameValuePair x1 = new NameValuePair("x1", login.getUser());
    NameValuePair x2 = new NameValuePair("x2", login.getPass());
    method.setRequestBody(new NameValuePair[] { x1, x2 });
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    try {//from   w  w w  . jav a2 s  .c o m
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            log.error("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody();
        String rb = new String(responseBody).trim();
        // Deal with the response.
        if (rb.startsWith("OK")) {
            autenticado = true;
            String[] rbLines = rb.split("\n");
            Token.setUrl(rbLines[1]);
        }
    } catch (HttpException he) {
        log.error("Fatal protocol violation: " + he.getMessage(), he);
    } catch (IOException ioe) {
        log.error("Fatal transport error: " + ioe.getMessage(), ioe);
    } finally {
        /*
         *  Release the connection.
        */
        method.releaseConnection();
    }

    return autenticado;
}

From source file:com.navercorp.pinpoint.plugin.httpclient3.HttpClientIT.java

@Test
public void hostConfig() throws Exception {
    HttpClient client = new HttpClient();
    client.getParams().setConnectionManagerTimeout(CONNECTION_TIMEOUT);
    client.getParams().setSoTimeout(SO_TIMEOUT);

    HostConfiguration config = new HostConfiguration();
    config.setHost("weather.naver.com", 80, "http");
    GetMethod method = new GetMethod("/rgn/cityWetrMain.nhn");

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    method.setQueryString(new NameValuePair[] { new NameValuePair("key2", "value2") });

    try {/*from   w  w w  .j  av  a  2s .c  o  m*/
        // Execute the method.
        client.executeMethod(config, method);
    } catch (Exception ignored) {
    } finally {
        method.releaseConnection();
    }

    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();
}

From source file:fr.dutra.confluence2wordpress.util.UrlUtils.java

private static URI followRedirectsInternal(URI url, int maxRedirections) {
    URI response = url;/*from  w w w.j  a v a  2  s  .  c o m*/
    HttpClient client = new HttpClient();
    DefaultHttpMethodRetryHandler handler = new DefaultHttpMethodRetryHandler(1, false);
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, handler);
    HttpMethod method = new HeadMethod(url.toASCIIString());
    //method.setRequestHeader("Accept-Language", locale.getLanguage() + ",en");
    method.setFollowRedirects(false);
    try {
        int statusCode = client.executeMethod(method);
        if ((statusCode == HttpStatus.SC_MOVED_PERMANENTLY) | (statusCode == HttpStatus.SC_MOVED_TEMPORARILY)) {
            if (maxRedirections > 0) {
                Header location = method.getResponseHeader("Location");
                if (!location.getValue().equals("")) {
                    // recursively check URL until it's not redirected any more
                    // locations can be relative to previous URL
                    URI target = url.resolve(location.getValue());
                    response = followRedirectsInternal(target, maxRedirections - 1);
                }
            }
        }
    } catch (Exception e) {
        //HttpClient can also throw IllegalArgumentException when URLs are malformed
    }
    return response;
}

From source file:com.pureinfo.force.net.impl.HttpUtilImpl.java

/**
 * @see com.pureinfo.force.net.IHttpUtil#getContent(String, NameValuePair[],
 *      String, String)/*from ww  w. ja  va  2s  .  co  m*/
 */
public String getContent(String _sUrl, NameValuePair[] _args, String _sRequestCharset, String _sResponseCharset)
        throws IOTransferException {
    if (_sRequestCharset == null) {
        _sRequestCharset = "utf-8";
    }

    //1. to create http client and set proxy
    HttpClient client = new HttpClient();
    if (m_proxyHost != null) {
        client.getHostConfiguration().setProxyHost(m_proxyHost);
        if (m_sProxyUser != null & m_sProxyPassword != null) {
            client.getState().setProxyCredentials(//
                    new AuthScope(m_proxyHost.getHostName(), m_proxyHost.getPort()),
                    new UsernamePasswordCredentials(m_sProxyUser, m_sProxyPassword));
        }
    }

    //2. to create post
    PostMethod method = new PostMethod(_sUrl);
    if (m_nRetryCount > 0) {
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, //
                new DefaultHttpMethodRetryHandler(m_nRetryCount, false));
    }
    method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=" + _sRequestCharset);
    for (int i = 0; _args != null && i < _args.length; i++) {
        method.addParameter(_args[i]);
    }

    //3. to send request and read response
    String sResponse;
    try {
        client.executeMethod(method);
        sResponse = method.getResponseBodyAsString();
        if (!method.getRequestCharSet().equals(_sRequestCharset)) {
            sResponse = new String(sResponse.getBytes(), _sResponseCharset);
        }
        return sResponse;
    } catch (Exception ex) {
        throw new IOTransferException(_sUrl, ex);
    } finally {
        method.releaseConnection();
    }
}