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:org.abstracthorizon.proximity.storage.remote.CommonsHttpClientRemotePeer.java

/**
 * Execute method./*from  w w  w .  j ava  2 s .  c  om*/
 * 
 * @param method the method
 * 
 * @return the int
 */
protected int executeMethod(HttpMethod method) {
    if (getUserAgentString() != null) {
        method.setRequestHeader(new Header("user-agent", getUserAgentString()));
    }
    method.setRequestHeader(new Header("accept", "*/*"));
    method.setRequestHeader(new Header("accept-language", "en-us"));
    method.setRequestHeader(new Header("accept-encoding", "gzip, identity"));
    method.setRequestHeader(new Header("connection", "Keep-Alive"));
    method.setRequestHeader(new Header("cache-control", "no-cache"));
    // TODO: fix for #93
    // method.setFollowRedirects(isFollowRedirection());
    method.setFollowRedirects(true);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, httpRetryHandler);
    method.setQueryString(getQueryString());
    int resultCode = 0;
    try {
        resultCode = getHttpClient().executeMethod(httpConfiguration, method);
    } catch (HttpException ex) {
        logger.error("Protocol error while executing " + method.getName() + " method", ex);
    } catch (IOException ex) {
        logger.error("Tranport error while executing " + method.getName() + " method", ex);
    }
    return resultCode;
}

From source file:org.alfresco.web.bean.ajax.PresenceProxyBean.java

/**
 * Perform request/*  www  . j  a  v a  2 s  .  c o m*/
 */
public String getUrlResponse(String requestUrl) {
    String response = "";
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(requestUrl);
    method.setRequestHeader("Accept", "*/*");
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
    try {
        int statusCode = client.executeMethod(method);
        if (statusCode == HttpStatus.SC_OK) {
            response = method.getResponseBodyAsString();
        } else {
            response = method.getStatusText();
        }
    } catch (HttpException e) {
        response = e.getMessage();
    } catch (IOException e) {
        response = e.getMessage();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    return response;
}

From source file:org.apache.asterix.aoya.Utils.java

private static InputStream executeHTTPCall(HttpMethod method) throws HttpException, IOException {
    HttpClient client = new HttpClient();
    HttpMethodRetryHandler noop = new HttpMethodRetryHandler() {
        @Override//w w  w  .  jav a  2  s . c  o m
        public boolean retryMethod(final HttpMethod method, final IOException exception, int executionCount) {
            return false;
        }
    };
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, noop);
    client.executeMethod(method);
    return method.getResponseBodyAsStream();
}

From source file:org.apache.asterix.test.aql.TestsUtils.java

public static InputStream executeQuery(String str, OutputFormat fmt) throws Exception {
    final String url = "http://localhost:19002/query";

    HttpMethodBase method = null;//from   w  w  w.  j  a v a  2  s .  c o  m
    if (str.length() + url.length() < MAX_URL_LENGTH) {
        //Use GET for small-ish queries
        method = new GetMethod(url);
        method.setQueryString(new NameValuePair[] { new NameValuePair("query", str) });
    } else {
        //Use POST for bigger ones to avoid 413 FULL_HEAD
        method = new PostMethod(url);
        ((PostMethod) method).setRequestEntity(new StringRequestEntity(str));
    }

    //Set accepted output response type
    method.setRequestHeader("Accept", fmt.mimeType());
    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    executeHttpMethod(method);
    return method.getResponseBodyAsStream();
}

From source file:org.apache.axis2.mtom.EchoRawMTOMFaultReportTest.java

public void testEchoFaultSync() throws Exception {
    HttpClient client = new HttpClient();

    PostMethod httppost = new PostMethod(
            "http://127.0.0.1:" + (UtilServer.TESTING_PORT) + "/axis2/services/EchoService/mtomSample");

    HttpMethodRetryHandler myretryhandler = new HttpMethodRetryHandler() {
        public boolean retryMethod(final HttpMethod method, final IOException exception, int executionCount) {
            if (executionCount >= 10) {
                return false;
            }//from w w  w  .j  a v  a 2 s  .c o m
            if (exception instanceof NoHttpResponseException) {
                return true;
            }
            if (!method.isRequestSent()) {
                return true;
            }
            // otherwise do not retry
            return false;
        }
    };
    httppost.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, myretryhandler);
    httppost.setRequestEntity(new InputStreamRequestEntity(
            new FileInputStream(TestingUtils.prefixBaseDirectory("test-resources/mtom/wmtom.bin"))));

    httppost.setRequestHeader("Content-Type",
            "multipart/related; boundary=--MIMEBoundary258DE2D105298B756D; type=\"application/xop+xml\"; start=\"<0.15B50EF49317518B01@apache.org>\"; start-info=\"application/soap+xml\"");
    try {
        client.executeMethod(httppost);

        if (httppost.getStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR) {

            // TODO: There is a missing wsa:Action header in the SOAP message.  Fix or look for correct fault text!

            //                assertEquals("HTTP/1.1 500 Internal server error",
            //                             httppost.getStatusLine().toString());
        }
    } catch (NoHttpResponseException e) {
    } finally {
        httppost.releaseConnection();
    }
}

From source file:org.apache.axis2.saaj.AttachmentTest.java

private boolean isNetworkedResourceAvailable(String url) {
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(url);
    client.getHttpConnectionManager().getParams().setConnectionTimeout(1000);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(1, false));

    try {/*from  w  w  w. j  a  v a  2s.  co  m*/
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            return false;
        }
        //byte[] responseBody = method.getResponseBody();
    } catch (HttpException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        method.releaseConnection();
    }
    return true;
}

From source file:org.apache.axis2.saaj.SOAPConnectionTest.java

private boolean isNetworkedResourceAvailable(String url) {
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(url);
    client.getHttpConnectionManager().getParams().setConnectionTimeout(1000);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(1, false));

    try {/*ww  w. j  a va 2 s.  c  o  m*/
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            return false;
        }

    } catch (HttpException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        method.releaseConnection();
    }
    return true;
}

From source file:org.apache.commons.httpclient.demo.ClientLogin.java

public static void main(String[] args) {
    HttpClient httpClient = new HttpClient();
    // //from  w  w w  . j a  v a2 s . c o m
    //httpClient.getHostConfiguration().setProxy("90.0.12.21", 808);

    GetMethod get_method = new GetMethod(
            "http://172.20.250.54:7123/kuandai/login_in.jsp?yhm=runwaytest&yhmm=txxlkjfd");

    try {
        int statusCode = httpClient.executeMethod(get_method);
        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + get_method.getStatusLine());
        }

    } catch (Exception e) {
        e.printStackTrace(System.out);
    } finally {
        // Release the connection.
        get_method.releaseConnection();
    }

    // GetMethod get_method2 = new
    // GetMethod("http://172.20.250.54:7123/kuandai/doAction.jsp?action=aRouterIpStatus&param0=10.16.16.1&area=1&count=1");
    // byte[] responseBody = null;
    // try {
    // // Provide custom retry handler is necessary
    // get_method2.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
    // new DefaultHttpMethodRetryHandler(3, false));
    // int statusCode = httpClient.executeMethod(get_method2);
    //
    // if (statusCode != HttpStatus.SC_OK) {
    // System.err.println("Method failed: " + get_method2.getStatusLine());
    // }
    //
    // //
    // InputStream in = get_method2.getResponseBodyAsStream();
    // if (in != null) {
    // byte[] tmp = new byte[4096];
    // int bytesRead = 0;
    // ByteArrayOutputStream buffer = new ByteArrayOutputStream(1024);
    // while ((bytesRead = in.read(tmp)) != -1) {
    // buffer.write(tmp, 0, bytesRead);
    // }
    // responseBody = buffer.toByteArray();
    // }
    // System.out.println(new String(responseBody));
    // } catch (IOException e) {
    // e.printStackTrace(System.out);
    // } finally {
    // get_method2.releaseConnection();
    // }
    GetMethod get_method2 = new GetMethod(
            "http://172.20.250.54:7123/kuandai/queryrstgraph.jsp?hosts=00system00&items=UA&graph=graph&Avgvalue=1&DataDate=2007-10-31");
    byte[] responseBody = null;
    try {
        // Provide custom retry handler is necessary
        get_method2.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));
        int statusCode = httpClient.executeMethod(get_method2);

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

        // 
        InputStream in = get_method2.getResponseBodyAsStream();
        if (in != null) {
            byte[] tmp = new byte[4096];
            int bytesRead = 0;
            ByteArrayOutputStream buffer = new ByteArrayOutputStream(1024);
            while ((bytesRead = in.read(tmp)) != -1) {
                buffer.write(tmp, 0, bytesRead);
            }
            responseBody = buffer.toByteArray();
        }
        System.out.println(new String(responseBody));
    } catch (IOException e) {
        e.printStackTrace(System.out);
    } finally {
        get_method2.releaseConnection();
    }
    try {
        Parser parser = Parser.createParser(new String(responseBody, "GBK"), "GBK");
        // String filterStr = "";
        // NodeFilter filter = new StringFilter(filterStr);
        // NodeList fonts = parser.extractAllNodesThatMatch(filter);
        // for (SimpleNodeIterator iter = fonts.elements();
        // iter.hasMoreNodes();) {
        // Node tag = iter.nextNode();
        // try {
        // System.out.println("tag.getText() = " + tag.getText());
        // } catch (Exception e) {
        // e.printStackTrace(System.out);
        // }
        // }

        String filterStr = "param";
        NodeFilter filter = new TagNameFilter(filterStr);
        NodeList tables = parser.extractAllNodesThatMatch(filter);
        for (SimpleNodeIterator iter = tables.elements(); iter.hasMoreNodes();) {
            Tag tag = (Tag) iter.nextNode();
            try {
                // System.out.println("tag.getTagName() = " +
                // tag.getTagName());
                // System.out.println("tag.getAttribute(\"name\") = " +
                // tag.getAttribute("name"));
                // System.out.println("tag.getAttribute(\"value\") = " +
                // tag.getAttribute("value"));
                if (tag.getAttribute("name").equals("sampleValues_0")) {
                    String v = tag.getAttribute("value");
                    String value = null;
                    if (v.endsWith(",")) {
                        value = v.substring(0, v.length() - 1);
                    } else {
                        value = v;
                    }
                    int index = value.lastIndexOf(",");
                    String total = value.substring(index + 1, value.length());
                    System.out.println("total = " + total);
                }
            } catch (Exception e) {
                e.printStackTrace(System.out);
            }
        }
    } catch (Exception e) {
        e.printStackTrace(System.out);
    }
}

From source file:org.apache.commons.httpclient.demo.GetSample.java

public static void main(String[] args) {
    //HttpClient//from w w  w . j a  va 2 s  .c  o m
    HttpClient httpClient = new HttpClient();
    //
    //httpClient.getHostConfiguration().setProxy("90.0.12.21",808);
    //GET
    GetMethod getMethod = new GetMethod("http://www.baidu.com");
    //GetMethod getMethod = new GetMethod("http://10.164.80.52/dav/5000/moban.rar");
    //
    getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
    try {
        //getMethod
        int statusCode = httpClient.executeMethod(getMethod);
        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + getMethod.getStatusLine());
        }
        //
        byte[] responseBody = getMethod.getResponseBody();

        String serverfile = "Test_baidu.html";
        //String serverfile = "d:\\moban.rar";
        OutputStream serverout = new FileOutputStream(serverfile);

        serverout.write(responseBody);
        serverout.flush();
        serverout.close();

        //
        //System.out.println(new String(responseBody));
        System.out.println("OK!");
    } catch (HttpException e) {
        //
        System.out.println("Please check your provided http address!");
        e.printStackTrace();
    } catch (IOException e) {
        //
        e.printStackTrace();
    } finally {
        //
        getMethod.releaseConnection();
    }
}

From source file:org.apache.hadoop.chukwa.datacollection.sender.ChukwaHttpSender.java

/**
 * Handles the HTTP post. Throws HttpException on failure
 *///from www . j  av  a2s  . com
@SuppressWarnings("deprecation")
private void doPost(PostMethod method, RequestEntity data, String dest) throws IOException, HttpException {

    HttpMethodParams pars = method.getParams();
    pars.setParameter(HttpMethodParams.RETRY_HANDLER, (Object) new HttpMethodRetryHandler() {
        public boolean retryMethod(HttpMethod m, IOException e, int exec) {
            return !(e instanceof java.net.ConnectException) && (exec < MAX_RETRIES_PER_COLLECTOR);
        }
    });
    method.setParams(pars);
    method.setPath(dest);

    //send it across the network
    method.setRequestEntity(data);

    log.info("HTTP post to " + dest + " length = " + data.getContentLength());
    // Send POST request

    client.setTimeout(8000);
    int statusCode = client.executeMethod(method);

    if (statusCode != HttpStatus.SC_OK) {
        log.error("HTTP post response statusCode: " + statusCode + ", statusLine: " + method.getStatusLine());
        //do something aggressive here
        throw new HttpException("got back a failure from server");
    }
    //implicitly "else"
    log.info(
            "got success back from the remote collector; response length " + method.getResponseContentLength());

    //FIXME: should parse acks here
    InputStream rstream = null;

    // Get the response body
    byte[] resp_buf = method.getResponseBody();
    rstream = new ByteArrayInputStream(resp_buf);
    BufferedReader br = new BufferedReader(new InputStreamReader(rstream));
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println("response: " + line);
    }
}