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.taobao.ad.easyschedule.commons.utils.WangWangUtil.java

/**
 * ??/*from  w w  w .  ja v a 2  s.  c o 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:name.chengchao.myhttpclient.version3_1.HttpClient3Util.java

/**
 * ?url?ResponseBody,method=get/*from w  w w.  j  av a  2s.com*/
 * 
 * @param url exp:http://192.168.1.1:8080/dir/target.html
 * @return byte[]?
 */
public static byte[] getDataFromUrl(String url, int timeout) {
    if (StringUtils.isBlank(url)) {
        logger.error("url is blank!");
        return null;
    }
    HttpClient httpClient = new HttpClient();
    // 
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(8000);
    // ?
    httpClient.getParams().setSoTimeout(timeout);
    GetMethod method = new GetMethod(url);

    // fix???
    method.setRequestHeader("Connection", "close");
    // ??1
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(1, false));
    try {
        int statusCode = httpClient.executeMethod(method);
        if (statusCode == HttpStatus.SC_OK) {
            return method.getResponseBody();
        } else {
            throw new RuntimeException("http request error,return code:" + statusCode + ",msg:"
                    + new String(method.getResponseBody()));
        }
    } catch (HttpException e) {
        method.abort();
        logger.error(e.getMessage());
    } catch (IOException e) {
        method.abort();
        logger.error(e.getMessage());
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return null;
}

From source file:name.chengchao.myhttpclient.version3_1.HttpClient3UtilError.java

/**
 * ?url?ResponseBody,method=get//  w  w w .  j av  a 2s .  c  om
 * 
 * @param url exp:http://192.168.1.1:8080/dir/target.html
 * @return byte[]?
 */
public static byte[] getDataFromUrl(String url, int timeout) {
    if (StringUtils.isBlank(url)) {
        logger.error("url is blank!");
        return null;
    }
    HttpClient httpClient = new HttpClient();
    // 
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(8000);
    // ?
    httpClient.getParams().setSoTimeout(timeout);
    GetMethod method = new GetMethod(url);

    // fix???
    // method.setRequestHeader("Connection", "close");
    // ??1
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(1, false));
    try {
        int statusCode = httpClient.executeMethod(method);
        if (statusCode == HttpStatus.SC_OK) {
            return method.getResponseBody();
        } else {
            throw new RuntimeException("http request error,return code:" + statusCode + ",msg:"
                    + new String(method.getResponseBody()));
        }
    } catch (HttpException e) {
        method.abort();
        logger.error(e.getMessage());
    } catch (IOException e) {
        method.abort();
        logger.error(e.getMessage());
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return null;
}

From source file:com.ibm.stocator.fs.swift.SwiftAPIDirect.java

/**
 * GET object//from   w w w  .jav  a  2s.c  o  m
 *
 * @param path path to object
 * @param authToken authentication token
 * @param bytesFrom from from
 * @param bytesTo bytes to
 * @return SwiftGETResponse that includes input stream and length
 * @throws IOException if network errors
 */
public static SwiftGETResponse getObject(Path path, String authToken, long bytesFrom, long bytesTo)
        throws IOException {
    GetMethod method = new GetMethod(path.toString());
    method.addRequestHeader(new Header("X-Auth-Token", authToken));
    if (bytesTo > 0) {
        final String rangeValue = String.format("bytes=%d-%d", bytesFrom, bytesTo);
        method.addRequestHeader(new Header(Constants.RANGES_HTTP_HEADER, rangeValue));
    }
    HttpMethodParams methodParams = method.getParams();
    methodParams.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
    methodParams.setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 15000);
    methodParams.setSoTimeout(60000);
    method.addRequestHeader(Constants.USER_AGENT_HTTP_HEADER, Constants.STOCATOR_USER_AGENT);
    final HttpClient client = new HttpClient();
    int statusCode = client.executeMethod(method);
    SwiftInputStreamWrapper httpStream = new SwiftInputStreamWrapper(method);
    SwiftGETResponse getResponse = new SwiftGETResponse(httpStream, method.getResponseContentLength());
    return getResponse;
}

From source file:edu.uci.ics.external.connector.asterixdb.ConnectorUtils.java

public static DatasetInfo retrieveDatasetInfo(StorageParameter storageParameter) throws Exception {
    HttpClient client = new HttpClient();
    String requestStr = storageParameter.getServiceURL() + "/connector" + "?dataverseName="
            + storageParameter.getDataverseName() + "&datasetName=" + storageParameter.getDatasetName();
    // Create a method instance.
    GetMethod method = new GetMethod(requestStr);

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

    // Deals with the response.
    // Executes the method.
    try {/*w  w w.  j a  v  a  2s .  c  o m*/
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + method.getStatusLine());
        }

        // Deals with the response.
        JSONTokener tokener = new JSONTokener(new InputStreamReader(method.getResponseBodyAsStream()));
        JSONObject response = new JSONObject(tokener);

        // Checks if there are errors.
        String error = "error";
        if (response.has(error)) {
            throw new IllegalStateException("AsterixDB returned errors: " + response.getString(error));
        }

        // Extracts record type and file partitions.
        boolean temp = extractTempInfo(response);
        ARecordType recordType = extractRecordType(response);
        List<FilePartition> filePartitions = extractFilePartitions(response);
        IFileSplitProvider fileSplitProvider = createFileSplitProvider(storageParameter, filePartitions);
        String[] locations = getScanLocationConstraints(filePartitions, storageParameter.getIpToNcNames());
        String[] primaryKeys = response.getString("keys").split(",");
        DatasetInfo datasetInfo = new DatasetInfo(locations, fileSplitProvider, recordType, primaryKeys, temp);
        return datasetInfo;
    } catch (Exception e) {
        throw e;
    } finally {
        method.releaseConnection();
    }
}

From source file:name.chengchao.myhttpclient.version3_1.HttpClient3UtilUseManager.java

/**
 * ?url?ResponseBody,method=get/* w  w w. j av  a 2  s.  c  om*/
 * 
 * @param url exp:http://192.168.1.1:8080/dir/target.html
 * @return byte[]?
 */
public static byte[] getDataFromUrl(String url, int timeout) {
    if (StringUtils.isBlank(url)) {
        logger.error("url is blank!");
        return null;
    }
    HttpClient httpClient = new HttpClient(connectionManager);
    // 
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(8000);
    // ?
    httpClient.getParams().setSoTimeout(timeout);
    GetMethod method = new GetMethod(url);

    // fix???
    // method.setRequestHeader("Connection", "close");
    // ??1
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(1, false));
    try {
        int statusCode = httpClient.executeMethod(method);
        if (statusCode == HttpStatus.SC_OK) {
            return method.getResponseBody();
        } else {
            throw new RuntimeException("http request error,return code:" + statusCode + ",msg:"
                    + new String(method.getResponseBody()));
        }
    } catch (HttpException e) {
        method.abort();
        logger.error(e.getMessage());
    } catch (IOException e) {
        method.abort();
        logger.error(e.getMessage());
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return null;
}

From source file:com.github.adam6806.mediarequest.sonarrservice.SonarrService.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {

    try {//  www  . jav a  2  s  .  c  o m
        HttpClient httpClient = new HttpClient();
        String term = request.getParameter("searchTerm");
        URI uri = new URIBuilder().setScheme(sonarrURL.getProtocol()).setHost(sonarrURL.getHost())
                .setPort(sonarrURL.getPort()).setPath("/api/Series/lookup").setParameter("term", term)
                .setParameter("apikey", apiKey).build();
        GetMethod getMethod = new GetMethod(uri.toString());
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));
        httpClient.executeMethod(getMethod);
        String responseBody = getMethod.getResponseBodyAsString();
        response.getWriter().write(responseBody);
    } catch (URISyntaxException ex) {
        Logger.getLogger(SonarrService.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(SonarrService.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.github.adam6806.mediarequest.couchpotatoservice.CouchPotatoService.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {

    try {/*from   w ww .j  a  va  2  s  .c o m*/
        HttpClient httpClient = new HttpClient();
        String term = request.getParameter("searchTerm");
        URI uri = new URIBuilder().setScheme(couchPotatoURL.getProtocol()).setHost(couchPotatoURL.getHost())
                .setPort(couchPotatoURL.getPort()).setPath("/api/" + apiKey + "/movie.search")
                .setParameter("q", term).build();
        GetMethod getMethod = new GetMethod(uri.toString());
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));
        httpClient.executeMethod(getMethod);
        String responseBody = getMethod.getResponseBodyAsString();
        response.getWriter().write(responseBody);
    } catch (URISyntaxException ex) {
        Logger.getLogger(CouchPotatoService.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(CouchPotatoService.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.voidsearch.voidbase.client.VoidBaseHttpClient.java

public byte[] get(String query) throws Exception {

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

    StringBuilder sb = new StringBuilder();

    // TODO : add a content dependent fetch

    try {//  w w  w.  j a  va2s .  c o  m
        int statusCode = client.executeMethod(method);

        if (statusCode == HttpStatus.SC_OK) {
            InputStreamReader is = new InputStreamReader(method.getResponseBodyAsStream());
            BufferedReader in = new BufferedReader(is);

            String line = null;
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
        }

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

    return (sb.toString()).getBytes();

}

From source file:AnnotationClient.java

public String request(HttpMethod method) throws AnnotationException {

    String response = null;//from  w  ww .ja v 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.

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

    } 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;

}