Search in sources :

Example 11 with DefaultHttpMethodRetryHandler

use of org.apache.commons.httpclient.DefaultHttpMethodRetryHandler in project openhab1-addons by openhab.

the class Telegram method sendTelegram.

@ActionDoc(text = "Sends a Telegram via Telegram REST API - direct message")
public static boolean sendTelegram(@ParamDoc(name = "group") String group, @ParamDoc(name = "message") String message) {
    if (groupTokens.get(group) == null) {
        logger.error("Bot '{}' not defined, action skipped", group);
        return false;
    }
    String url = String.format(TELEGRAM_URL, groupTokens.get(group).getToken());
    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(url);
    postMethod.getParams().setContentCharset("UTF-8");
    postMethod.getParams().setSoTimeout(HTTP_TIMEOUT);
    postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
    NameValuePair[] data = { new NameValuePair("chat_id", groupTokens.get(group).getChatId()), new NameValuePair("text", message) };
    postMethod.setRequestBody(data);
    try {
        int statusCode = client.executeMethod(postMethod);
        if (statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_ACCEPTED) {
            return true;
        }
        if (statusCode != HttpStatus.SC_OK) {
            logger.warn("Method failed: {}", postMethod.getStatusLine());
            return false;
        }
        InputStream tmpResponseStream = postMethod.getResponseBodyAsStream();
        Header encodingHeader = postMethod.getResponseHeader("Content-Encoding");
        if (encodingHeader != null) {
            for (HeaderElement ehElem : encodingHeader.getElements()) {
                if (ehElem.toString().matches(".*gzip.*")) {
                    tmpResponseStream = new GZIPInputStream(tmpResponseStream);
                    logger.debug("GZipped InputStream from {}", url);
                } else if (ehElem.toString().matches(".*deflate.*")) {
                    tmpResponseStream = new InflaterInputStream(tmpResponseStream);
                    logger.debug("Deflated InputStream from {}", url);
                }
            }
        }
        String responseBody = IOUtils.toString(tmpResponseStream);
        if (!responseBody.isEmpty()) {
            logger.debug(responseBody);
        }
    } catch (HttpException e) {
        logger.error("Fatal protocol violation: {}", e.toString());
        return false;
    } catch (IOException e) {
        logger.error("Fatal transport error: {}", e.toString());
        return false;
    } finally {
        postMethod.releaseConnection();
    }
    return true;
}
Also used : NameValuePair(org.apache.commons.httpclient.NameValuePair) PostMethod(org.apache.commons.httpclient.methods.PostMethod) GZIPInputStream(java.util.zip.GZIPInputStream) InflaterInputStream(java.util.zip.InflaterInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) ImageInputStream(javax.imageio.stream.ImageInputStream) InputStream(java.io.InputStream) HeaderElement(org.apache.commons.httpclient.HeaderElement) InflaterInputStream(java.util.zip.InflaterInputStream) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) IOException(java.io.IOException) GZIPInputStream(java.util.zip.GZIPInputStream) Header(org.apache.commons.httpclient.Header) HttpClient(org.apache.commons.httpclient.HttpClient) HttpException(org.apache.commons.httpclient.HttpException) ActionDoc(org.openhab.core.scriptengine.action.ActionDoc)

Example 12 with DefaultHttpMethodRetryHandler

use of org.apache.commons.httpclient.DefaultHttpMethodRetryHandler in project hadoop by apache.

the class SwiftRestClient method perform.

/**
   * Performs the HTTP request, validates the response code and returns
   * the received data. HTTP Status codes are converted into exceptions.
   * @param reason why is this operation taking place. Used for statistics
   * @param uri URI to source
   * @param processor HttpMethodProcessor
   * @param <M> method
   * @param <R> result type
   * @return result of HTTP request
   * @throws IOException IO problems
   * @throws SwiftBadRequestException the status code indicated "Bad request"
   * @throws SwiftInvalidResponseException the status code is out of range
   * for the action (excluding 404 responses)
   * @throws SwiftInternalStateException the internal state of this client
   * is invalid
   * @throws FileNotFoundException a 404 response was returned
   */
private <M extends HttpMethod, R> R perform(String reason, URI uri, HttpMethodProcessor<M, R> processor) throws IOException, SwiftBadRequestException, SwiftInternalStateException, SwiftInvalidResponseException, FileNotFoundException {
    checkNotNull(uri);
    checkNotNull(processor);
    final M method = processor.createMethod(uri.toString());
    //retry policy
    HttpMethodParams methodParams = method.getParams();
    methodParams.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(retryCount, false));
    methodParams.setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, connectTimeout);
    methodParams.setSoTimeout(socketTimeout);
    method.addRequestHeader(HEADER_USER_AGENT, SWIFT_USER_AGENT);
    Duration duration = new Duration();
    boolean success = false;
    try {
        int statusCode = 0;
        try {
            statusCode = exec(method);
        } catch (IOException e) {
            //rethrow with extra diagnostics and wiki links
            throw ExceptionDiags.wrapException(uri.toString(), method.getName(), e);
        }
        //look at the response and see if it was valid or not.
        //Valid is more than a simple 200; even 404 "not found" is considered
        //valid -which it is for many methods.
        //validate the allowed status code for this operation
        int[] allowedStatusCodes = processor.getAllowedStatusCodes();
        boolean validResponse = isStatusCodeExpected(statusCode, allowedStatusCodes);
        if (!validResponse) {
            IOException ioe = buildException(uri, method, statusCode);
            throw ioe;
        }
        R r = processor.extractResult(method);
        success = true;
        return r;
    } catch (IOException e) {
        //release the connection -always
        method.releaseConnection();
        throw e;
    } finally {
        duration.finished();
        durationStats.add(method.getName() + " " + reason, duration, success);
    }
}
Also used : DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) Duration(org.apache.hadoop.fs.swift.util.Duration) IOException(java.io.IOException) HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams) Endpoint(org.apache.hadoop.fs.swift.auth.entities.Endpoint)

Example 13 with DefaultHttpMethodRetryHandler

use of org.apache.commons.httpclient.DefaultHttpMethodRetryHandler in project twitter-2-weibo by rjyo.

the class HttpClient method httpRequest.

public Response httpRequest(HttpMethod method, Boolean WithTokenHeader) throws WeiboException {
    InetAddress ipaddr;
    int responseCode = -1;
    try {
        ipaddr = InetAddress.getLocalHost();
        List<Header> headers = new ArrayList<Header>();
        if (WithTokenHeader) {
            if (token == null) {
                throw new IllegalStateException("Oauth2 token is not set!");
            }
            headers.add(new Header("Authorization", "OAuth2 " + token));
            headers.add(new Header("API-RemoteIP", ipaddr.getHostAddress()));
            client.getHostConfiguration().getParams().setParameter("http.default-headers", headers);
            for (Header hd : headers) {
                log(hd.getName() + ": " + hd.getValue());
            }
        }
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
        client.executeMethod(method);
        Header[] resHeader = method.getResponseHeaders();
        responseCode = method.getStatusCode();
        log("Response:");
        log("https StatusCode:" + String.valueOf(responseCode));
        for (Header header : resHeader) {
            log(header.getName() + ":" + header.getValue());
        }
        Response response = new Response();
        response.setResponseAsString(method.getResponseBodyAsString());
        log(response.toString() + "\n");
        if (responseCode != OK) {
            try {
                throw new WeiboException(getCause(responseCode), response.asJSONObject(), method.getStatusCode());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return response;
    } catch (IOException ioe) {
        throw new WeiboException(ioe.getMessage(), ioe, responseCode);
    } finally {
        method.releaseConnection();
    }
}
Also used : WeiboException(weibo4j.model.WeiboException) Header(org.apache.commons.httpclient.Header) ArrayList(java.util.ArrayList) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) JSONException(weibo4j.org.json.JSONException) IOException(java.io.IOException) InetAddress(java.net.InetAddress)

Example 14 with DefaultHttpMethodRetryHandler

use of org.apache.commons.httpclient.DefaultHttpMethodRetryHandler in project pinpoint by naver.

the class HttpClientIT method hostConfig.

@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 {
        // Execute the method.
        client.executeMethod(config, method);
    } catch (Exception ignored) {
    } finally {
        method.releaseConnection();
    }
    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();
}
Also used : NameValuePair(org.apache.commons.httpclient.NameValuePair) HostConfiguration(org.apache.commons.httpclient.HostConfiguration) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) PluginTestVerifier(com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier) Test(org.junit.Test)

Example 15 with DefaultHttpMethodRetryHandler

use of org.apache.commons.httpclient.DefaultHttpMethodRetryHandler in project zaproxy by zaproxy.

the class HttpSender method setMaxRetriesOnIOError.

/**
     * Sets the maximum number of retries of an unsuccessful request caused by I/O errors.
     * <p>
     * The default number of retries is 3.
     *
     * @param retries the number of retries
     * @throws IllegalArgumentException if {@code retries} is negative.
     * @since 2.4.0
     */
public void setMaxRetriesOnIOError(int retries) {
    if (retries < 0) {
        throw new IllegalArgumentException("Parameter retries must be greater or equal to zero.");
    }
    HttpMethodRetryHandler retryHandler = new DefaultHttpMethodRetryHandler(retries, false);
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler);
    clientViaProxy.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler);
}
Also used : HttpMethodRetryHandler(org.apache.commons.httpclient.HttpMethodRetryHandler) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler)

Aggregations

DefaultHttpMethodRetryHandler (org.apache.commons.httpclient.DefaultHttpMethodRetryHandler)17 IOException (java.io.IOException)12 HttpClient (org.apache.commons.httpclient.HttpClient)12 HttpException (org.apache.commons.httpclient.HttpException)10 GetMethod (org.apache.commons.httpclient.methods.GetMethod)6 PostMethod (org.apache.commons.httpclient.methods.PostMethod)6 Header (org.apache.commons.httpclient.Header)5 NameValuePair (org.apache.commons.httpclient.NameValuePair)5 HttpMethod (org.apache.commons.httpclient.HttpMethod)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)3 PluginTestVerifier (com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier)2 EngineUnavailableException (it.eng.spagobi.engines.talend.client.exception.EngineUnavailableException)2 ServiceInvocationFailedException (it.eng.spagobi.engines.talend.client.exception.ServiceInvocationFailedException)2 InputStream (java.io.InputStream)2 GZIPInputStream (java.util.zip.GZIPInputStream)2 InflaterInputStream (java.util.zip.InflaterInputStream)2 ImageInputStream (javax.imageio.stream.ImageInputStream)2 Credentials (org.apache.commons.httpclient.Credentials)2 HeaderElement (org.apache.commons.httpclient.HeaderElement)2