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:com.panoramagl.downloaders.PLHTTPFileDownloader.java

/**download methods*/

@Override// w  w  w . j a v  a  2 s . c o  m
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:edu.internet2.middleware.grouper.changeLog.esb2.consumer.EsbHttpPublisher.java

@Override
public boolean dispatchEvent(String eventJsonString, String consumerName) {
    // TODO Auto-generated method stub

    String urlString = GrouperLoaderConfig
            .getPropertyString("changeLog.consumer." + consumerName + ".publisher.url");
    String username = GrouperLoaderConfig
            .getPropertyString("changeLog.consumer." + consumerName + ".publisher.username", "");
    String password = GrouperLoaderConfig
            .getPropertyString("changeLog.consumer." + consumerName + ".publisher.password", "");
    if (LOG.isDebugEnabled()) {
        LOG.debug("Consumer name: " + consumerName + " sending " + GrouperUtil.indent(eventJsonString, false)
                + " to " + urlString);
    }//from   w w w.  j ava2s .  co m
    int retries = GrouperLoaderConfig
            .getPropertyInt("changeLog.consumer." + consumerName + ".publisher.retries", 0);
    int timeout = GrouperLoaderConfig
            .getPropertyInt("changeLog.consumer." + consumerName + ".publisher.timeout", 60000);
    PostMethod post = new PostMethod(urlString);
    post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(retries, false));
    post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, new Integer(timeout));
    post.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    RequestEntity requestEntity;
    try {
        requestEntity = new StringRequestEntity(eventJsonString, "application/json", "utf-8");

        post.setRequestEntity(requestEntity);
        HttpClient httpClient = new HttpClient();
        if (!(username.equals(""))) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Authenticating using basic auth");
            }
            URL url = new URL(urlString);
            httpClient.getState().setCredentials(new AuthScope(null, url.getPort(), null),
                    new UsernamePasswordCredentials(username, password));
            httpClient.getParams().setAuthenticationPreemptive(true);
            post.setDoAuthentication(true);
        }
        int statusCode = httpClient.executeMethod(post);
        if (statusCode == 200) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Status code 200 recieved, event sent OK");
            }
            return true;
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Status code " + statusCode + " recieved, event send failed");
            }
            return false;
        }
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;
}

From source file:com.cloud.storage.template.MetalinkTemplateDownloader.java

protected GetMethod createRequest(String downloadUrl) {
    GetMethod request = new GetMethod(downloadUrl);
    request.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, myretryhandler);
    request.setFollowRedirects(true);//from ww  w  . j ava  2s . com
    if (!toFileSet) {
        String[] parts = downloadUrl.split("/");
        String filename = parts[parts.length - 1];
        _toFile = _toDir + File.separator + filename;
        toFileSet = true;
    }
    return request;
}

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

public static boolean postToServer(String s, String URI, StringBuffer response) {
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(URI);
    method.addParameter("OS", StringEscapeUtils
            .escapeHtml(System.getProperty("os.name") + "\t" + System.getProperty("os.version")));
    method.addParameter("JVM", StringEscapeUtils
            .escapeHtml(System.getProperty("java.version") + "\t" + System.getProperty("java.vendor")));
    NameValuePair post = new NameValuePair();
    post.setName("post");
    post.setValue(StringEscapeUtils.escapeHtml(s));
    method.addParameter(post);/* ww w .j  a v a2s  .  c om*/

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

    return executeMethod(client, method, response);
}

From source file:buildhappy.tools.DownloadFile.java

/**
 * URL/*w  w  w.  j  av  a  2 s.  c o  m*/
 */
public String downloadFile(String url) {
    String filePath = null;
    //1.?HttpClient??
    HttpClient client = new HttpClient();
    //5s
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

    //2.?GetMethod?
    GetMethod getMethod = new GetMethod(url);
    //get5s
    getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
    //??
    getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

    //3.http get 
    try {
        int statusCode = client.executeMethod(getMethod);
        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed:" + getMethod.getStatusLine());
            filePath = null;
        }
        //4.?HTTP?
        InputStream in = getMethod.getResponseBodyAsStream();
        BufferedInputStream buffIn = new BufferedInputStream(in);
        //byte[] responseBody = null;
        String responseBody = null;
        StringBuffer strBuff = new StringBuffer();
        byte[] b = new byte[1024];
        int readByte = 0;
        while ((readByte = buffIn.read(b)) != -1) {
            strBuff.append(new String(b));
        }
        responseBody = strBuff.toString();
        //buffIn.read(responseBody, off, len)
        //byte[] responseBody = getMethod.getResponseBody();
        //?url????
        filePath = "temp\\" + getFileNameByUrl(url, getMethod.getResponseHeader("Content-Type").getValue());
        System.out.println(filePath + "--size:" + responseBody.length());
        saveToLocal(responseBody.getBytes(), filePath);
    } catch (HttpException e) {
        System.out.println("check your http address");
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //
        getMethod.releaseConnection();
    }
    return filePath;
}

From source file:com.gagein.crawler.FileDownLoader.java

public String downloadLink(String url, HtmlFileBean hfb) {
    /* 1.? HttpClinet ? */
    HttpClient httpClient = new HttpClient();
    //  Http  5s//from  ww  w  . j  av  a 2  s. com
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
    /* 2.? GetMethod ? */
    GetMethod getMethod = new GetMethod(url);
    //  get  5s
    getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
    // ??
    getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

    /* 3. HTTP GET  */
    try {
        int statusCode = httpClient.executeMethod(getMethod);
        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + getMethod.getStatusLine());
        }
        /* 4.? HTTP ? */
        byte[] responseBody = getMethod.getResponseBody();// ?

        // ? url ????
        url = FileUtils.getFileNameByUrl(url);

        saveToLocal(responseBody, hfb.getDirPath() + File.separator + url);
    } catch (HttpException e) {
        // ?????
        logger.debug("Please check your provided http " + "address!");
        e.printStackTrace();
    } catch (IOException e) {
        // ?
        logger.debug("?");
        e.printStackTrace();
    } finally {
        // 
        logger.debug("=======================" + url + "=============?");
        getMethod.releaseConnection();
    }
    return hfb.getDirPath() + url;
}

From source file:com.unicauca.braim.http.HttpBraimClient.java

public Song[] GET_Songs(int page, String access_token, JButton bt_next_list, JButton bt_previous_list)
        throws IOException {
    if (page == 1) {
        bt_previous_list.setEnabled(false);
    } else {/*from   www . j  a v  a  2  s . c  o m*/
        bt_previous_list.setEnabled(true);
    }
    String token = "braim_token=" + access_token;
    String data = "page=" + page + "&per_page=10";
    GetMethod method = new GetMethod(api_url + "/api/v1/songs?" + token + "&" + data);

    Song[] songList = null;
    Gson gson = new Gson();

    try {
        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());
        }

        byte[] responseBody = method.getResponseBody();
        Integer total_pages = Integer.parseInt(method.getResponseHeader("total_pages").getValue());
        System.out.println("TOTAL SONG PAGES= " + method.getResponseHeader("total_pages"));
        String response = new String(responseBody, "UTF-8");
        songList = gson.fromJson(response, Song[].class);
        if (page == total_pages) {
            bt_next_list.setEnabled(false);
        } else {
            bt_next_list.setEnabled(true);
        }

    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(HttpBraimClient.class.getName()).log(Level.SEVERE, null, ex);
    }
    return songList;
}

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

/**
 * Gets the http method./*from ww  w. ja 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:br.org.acessobrasil.silvinha.util.versoes.VerificadorDeVersoes.java

public boolean verificarVersao(Versao versaoCliente) {
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(url);
    NameValuePair param = new NameValuePair("param", "check");
    method.setRequestBody(new NameValuePair[] { param });
    DefaultHttpMethodRetryHandler retryHandler = null;
    retryHandler = new DefaultHttpMethodRetryHandler(0, false);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler);
    try {//from  w w  w.  j  a  va2 s .  co  m
        //System.out.println(Silvinha.VERIFICADOR_VERSOES+client.getState().toString());
        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();
        Versao versaoServidor = null;
        try {
            versaoServidor = new Versao(rb);
        } catch (NumberFormatException nfe) {
            return false;
        }
        if (versaoCliente.compareTo(versaoServidor) < 0) {
            AtualizadorDeVersoes av = new AtualizadorDeVersoes(url);
            return av.confirmarAtualizacao();
        } else {
            return false;
        }
    } catch (HttpException he) {
        log.error("Fatal protocol violation: " + he.getMessage(), he);
        return false;
    } catch (IOException ioe) {
        log.error("Fatal transport error: " + ioe.getMessage(), ioe);
        return false;
    } catch (Exception e) {
        return false;
    } finally {
        //Release the connection.
        method.releaseConnection();
    }

}

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  a  v a 2  s .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();
        }
    }
}