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() 

Source Link

Usage

From source file:com.taobao.ad.easyschedule.commons.utils.MailUtil.java

/**
 * ??//from w  w w. j  ava  2s .co  m
 * 
 * @param list
 *            ?
 * @param subject
 * @param content
 */
public static void sendMail(String list, String subject, String content) {

    if ("false".equals(Constants.SENDMAIL) || StringUtils.isEmpty(list) || StringUtils.isEmpty(subject)) {
        return;
    }
    try {
        String command = Constants.MAIL_SEND_COMMAND;
        String strSubject = subject;
        if (subject.getBytes().length > 50) {
            strSubject = StringUtil.bSubstring(subject, 49);
        }
        String strContent = content;
        if (content.getBytes().length > 2046) {
            strContent = StringUtil.bSubstring(content, 2045);
        }
        command = command.replaceAll("#list#", URLEncoder.encode(list, "GBK"))
                .replaceAll("#subject#", URLEncoder.encode(strSubject, "GBK")).replaceAll("#content#",
                        URLEncoder.encode(StringUtils.isEmpty(strContent) ? "null" : strContent, "GBK"));
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(Constants.NOTIFY_API_CONN_TIMEOUT);
        GetMethod getMethod = new GetMethod(command);
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        for (int i = 1; i <= 3; i++) {
            try {
                int statusCode = client.executeMethod(getMethod);
                if (statusCode != HttpStatus.SC_OK) {
                    logger.error("MailUtil.sendMail statusCode:" + statusCode);
                    Thread.sleep(Constants.JOB_RETRY_WAITTIME);
                    continue;
                }
                String ret = getMethod.getResponseBodyAsString();
                if (!"OK".equals(ret)) {
                    logger.error("Send message failed[" + i + "];list:" + list + ";subject:" + subject
                            + ";content:" + content);
                    Thread.sleep(Constants.JOB_RETRY_WAITTIME);
                    continue;
                }
                break;
            } catch (Exception e) {
                logger.error("Send message failed[" + i + "]:" + e.getMessage());
                Thread.sleep(Constants.JOB_RETRY_WAITTIME);
                continue;
            }
        }
    } catch (Exception e) {
        logger.error("MailUtil.sendMail", e);
    }
}

From source file:com.taobao.ad.easyschedule.commons.utils.SmsUtil.java

/**
 * ??//from  w ww  . java2  s  .c  o m
 * 
 * @param list
 *            ?
 * @param subject
 * @param content
 */
public static void sendSMS(String list, String subject, String content) {
    if ("false".equals(Constants.SENDSMS) || StringUtils.isEmpty(list) || StringUtils.isEmpty(subject)) {
        return;
    }
    try {
        String command = Constants.SMS_SEND_COMMAND;
        String strSubject = subject;
        if (subject.getBytes().length > 50) {
            strSubject = StringUtil.bSubstring(subject, 49);
        }
        String strContent = subject;
        if (subject.getBytes().length > 150) {
            // ????content?subjectcontent??
            strContent = StringUtil.bSubstring(subject + ":" + content, 149);
        }
        command = command.replaceAll("#list#", URLEncoder.encode(list, "GBK"))
                .replaceAll("#subject#", URLEncoder.encode(strSubject, "GBK"))
                .replaceAll("#content#", URLEncoder.encode(strContent, "GBK"));
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(Constants.NOTIFY_API_CONN_TIMEOUT);
        GetMethod getMethod = new GetMethod(command);
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        for (int i = 1; i <= 3; i++) {
            try {
                int statusCode = client.executeMethod(getMethod);
                if (statusCode != HttpStatus.SC_OK) {
                    logger.error("SmsUtil.sendWangWang statusCode:" + statusCode);
                    sendSMSByShell(list, "es:" + subject);
                    Thread.sleep(Constants.JOB_RETRY_WAITTIME);
                    continue;
                }
                String ret = getMethod.getResponseBodyAsString();
                if (!"OK".equals(ret)) {
                    logger.error("Send message failed[" + i + "];list:" + list + ";subject:" + subject
                            + ";content:" + content);
                    sendSMSByShell(list, "es:" + subject);
                    Thread.sleep(Constants.JOB_RETRY_WAITTIME);
                    continue;
                }
                break;
            } catch (Exception e) {
                logger.error("Send message failed[" + i + "]:" + e.getMessage());
                Thread.sleep(Constants.JOB_RETRY_WAITTIME);
                continue;
            }
        }
    } catch (Exception e) {
        logger.error("SmsUtil.sendSMS", e);
    }
}

From source file:com.taobao.ad.easyschedule.commons.utils.WangWangUtil.java

/**
 * ??/*from  w  w w . j a v a2 s. co m*/
 * 
 * @param list
 *            ?
 * @param subject
 * @param content
 */
public static void sendWangWang(String list, String subject, String content) {

    if ("false".equals(Constants.SENDWANGWANG) || StringUtils.isEmpty(list) || StringUtils.isEmpty(subject)
            || StringUtils.isEmpty(content)) {
        return;
    }
    try {
        String command = Constants.WANGWANG_SEND_COMMAND;
        String strSubject = subject;
        if (subject.getBytes().length > 50) {
            strSubject = StringUtil.bSubstring(subject, 49);
        }
        String strContent = content;
        if (content.getBytes().length > 900) {
            strContent = StringUtil.bSubstring(content, 899);
        }
        command = command.replaceAll("#list#", URLEncoder.encode(list, "GBK"))
                .replaceAll("#subject#", URLEncoder.encode(strSubject, "GBK")).replaceAll("#content#",
                        URLEncoder.encode(StringUtils.isEmpty(strContent) ? "null" : strContent, "GBK"));
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(Constants.NOTIFY_API_CONN_TIMEOUT);
        GetMethod getMethod = new GetMethod(command);
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        for (int i = 1; i <= 3; i++) {
            try {
                int statusCode = client.executeMethod(getMethod);
                if (statusCode != HttpStatus.SC_OK) {
                    logger.error("WangWangUtil.sendWangWang statusCode:" + statusCode);
                    Thread.sleep(Constants.JOB_RETRY_WAITTIME);
                    continue;
                }
                String ret = getMethod.getResponseBodyAsString();
                if (!"OK".equals(ret)) {
                    logger.error("Send message failed[" + i + "];list:" + list + ";subject:" + subject
                            + ";content:" + content);
                    Thread.sleep(Constants.JOB_RETRY_WAITTIME);
                    continue;
                }
                break;
            } catch (Exception e) {
                logger.error("Send message failed[" + i + "]:" + e.getMessage());
                Thread.sleep(Constants.JOB_RETRY_WAITTIME);
                continue;
            }
        }
    } catch (Exception e) {
        logger.error("WangWangUtil.sendWangWang", e);
    }
}

From source file:com.eucalyptus.imaging.manifest.ImportImageManifest.java

@Override
public String getManifest(String location) throws EucalyptusCloudException {
    HttpClient client = new HttpClient();
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
    GetMethod method = new GetMethod(location);
    String s = null;//  ww  w.  j a  va 2s . com
    try {
        client.executeMethod(method);
        s = method.getResponseBodyAsString();
        if (s == null) {
            throw new EucalyptusCloudException("Can't download manifest from " + location + " content is null");
        }
    } catch (IOException ex) {
        throw new EucalyptusCloudException("Can't download manifest from " + location, ex);
    } finally {
        method.releaseConnection();
    }
    return s;
}

From source file:buildhappy.tools.DownloadFile.java

/**
 * URL//from  w w  w.  j a  v 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/* w  w w. j  av  a 2 s . co  m*/
    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.feilong.tools.net.httpclient3.HttpClientUtil.java

/**
 * Gets the http method.//from w w w  .  ja v  a  2s.c  om
 * 
 * @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:com.basho.riak.client.http.util.logging.LogNoHttpResponseRetryHandlerTest.java

/**
 * Test method for/*w w  w  .j a  va  2s .c o m*/
 * {@link com.basho.riak.client.http.util.logging.LogNoHttpResponseRetryHandler#retryMethod(org.apache.commons.httpclient.HttpMethod, java.io.IOException, int)}
 * .
 */
@Test
public void retry() {
    final HttpMethod method = new GetMethod();
    final IOException noHttpResponseException = new NoHttpResponseException();
    final IOException otherException = new ConnectTimeoutException();
    final int executionCount = 0;

    // when retry is called with a NoHtpResponseException
    // dump should be called on the appender
    LogNoHttpResponseRetryHandler handler = new LogNoHttpResponseRetryHandler(MOCK_APPENDER_NAME);
    boolean expected = new DefaultHttpMethodRetryHandler().retryMethod(method, noHttpResponseException,
            executionCount);
    boolean actual = handler.retryMethod(method, noHttpResponseException, executionCount);

    verify(mockAppender, times(1)).dump();

    assertEquals(expected, actual);

    expected = new DefaultHttpMethodRetryHandler().retryMethod(method, otherException, executionCount);
    actual = handler.retryMethod(method, otherException, executionCount);

    // dump must not have been called again!
    verify(mockAppender, times(1)).dump();

    // but the behaviour of the handler should still match the default
    assertEquals(expected, actual);
}

From source file:com.taobao.ad.easyschedule.action.schedule.ScheduleAction.java

private void controlRemoteInstance(String action) {
    try {//w ww.j a va2 s  .  com
        if (!checkInstance(instance)) {
            return;
        }
        Long currentTime = System.currentTimeMillis() / 1000;
        String token = TokenUtils.generateToken(currentTime.toString());
        HttpClient client = new HttpClient();
        int connTimeout = 1000;
        client.getHttpConnectionManager().getParams().setConnectionTimeout(connTimeout);
        GetMethod getMethod = null;
        String controlInterface = configBO.getStringValue(ConfigDO.CONFIG_KEY_INSTANCE_CONTROL_INTERFACE);
        controlInterface = controlInterface.replaceAll("#instance#", getInstanceName(instance));
        StringBuilder url = new StringBuilder(controlInterface);
        url = url.append(action);
        url = url.append("?").append(Const.TOKEN).append("=").append(token);
        url = url.append("&").append(Const.SIGNTIME).append("=").append(currentTime.toString());
        url = url.append("&").append("userName").append("=").append(getLogname());
        getMethod = new GetMethod(url.toString());
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        client.executeMethod(getMethod);
    } catch (Exception e) {
    }
}

From source file:com.ihelpoo.app.api.ApiClient.java

private static HttpClient getHttpClient() {
    HttpClient httpClient = new HttpClient();
    //  HttpClient  Cookie,?
    httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    //  ??//w  w  w  .java2  s  . co m
    httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
    //  
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(TIMEOUT_CONNECTION);
    //  ?
    httpClient.getHttpConnectionManager().getParams().setSoTimeout(TIMEOUT_SOCKET);
    //  
    httpClient.getParams().setContentCharset(UTF_8);
    return httpClient;
}