Search in sources :

Example 6 with DefaultHttpMethodRetryHandler

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

the class KM200Comm method sendDataToService.

/**
     * This function does the SEND http communication to the device
     *
     */
public Integer sendDataToService(String service, byte[] data) {
    // Create an instance of HttpClient.
    Integer rCode = null;
    if (client == null) {
        client = new HttpClient();
    }
    synchronized (client) {
        // Create a method instance.
        PostMethod method = new PostMethod("http://" + device.getIP4Address() + service);
        // Provide custom retry handler is necessary
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
        // Set the right header
        method.setRequestHeader("Accept", "application/json");
        method.addRequestHeader("User-Agent", "TeleHeater/2.2.3");
        method.setRequestEntity(new ByteArrayRequestEntity(data));
        try {
            rCode = client.executeMethod(method);
        } catch (Exception e) {
            logger.error("Failed to send data {}", e);
        } finally {
            // Release the connection.
            method.releaseConnection();
        }
        return rCode;
    }
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpClient(org.apache.commons.httpclient.HttpClient) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) JSONException(org.json.JSONException) GeneralSecurityException(java.security.GeneralSecurityException) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity)

Example 7 with DefaultHttpMethodRetryHandler

use of org.apache.commons.httpclient.DefaultHttpMethodRetryHandler in project zm-mailbox by Zimbra.

the class SoapHttpTransport method invoke.

public Element invoke(Element document, boolean raw, boolean noSession, String requestedAccountId, String changeToken, String tokenType, ResponseHandler respHandler) throws IOException, HttpException, ServiceException {
    PostMethod method = null;
    try {
        // Assemble post method.  Append document name, so that the request
        // type is written to the access log.
        String uri, query;
        int i = mUri.indexOf('?');
        if (i >= 0) {
            uri = mUri.substring(0, i);
            query = mUri.substring(i);
        } else {
            uri = mUri;
            query = "";
        }
        if (!uri.endsWith("/"))
            uri += '/';
        uri += getDocumentName(document);
        method = new PostMethod(uri + query);
        // Set user agent if it's specified.
        String agentName = getUserAgentName();
        if (agentName != null) {
            String agentVersion = getUserAgentVersion();
            if (agentVersion != null)
                agentName += " " + agentVersion;
            method.setRequestHeader(new Header("User-Agent", agentName));
        }
        // the content-type charset will determine encoding used
        // when we set the request body
        method.setRequestHeader("Content-Type", getRequestProtocol().getContentType());
        if (getClientIp() != null) {
            method.setRequestHeader(RemoteIP.X_ORIGINATING_IP_HEADER, getClientIp());
            if (ZimbraLog.misc.isDebugEnabled()) {
                ZimbraLog.misc.debug("set remote IP header [%s] to [%s]", RemoteIP.X_ORIGINATING_IP_HEADER, getClientIp());
            }
        }
        Element soapReq = generateSoapMessage(document, raw, noSession, requestedAccountId, changeToken, tokenType);
        String soapMessage = SoapProtocol.toString(soapReq, getPrettyPrint());
        HttpMethodParams params = method.getParams();
        method.setRequestEntity(new StringRequestEntity(soapMessage, null, "UTF-8"));
        if (getRequestProtocol().hasSOAPActionHeader())
            method.setRequestHeader("SOAPAction", mUri);
        if (mCustomHeaders != null) {
            for (Map.Entry<String, String> entry : mCustomHeaders.entrySet()) method.setRequestHeader(entry.getKey(), entry.getValue());
        }
        String host = method.getURI().getHost();
        HttpState state = HttpClientUtil.newHttpState(getAuthToken(), host, this.isAdmin());
        String trustedToken = getTrustedToken();
        if (trustedToken != null) {
            state.addCookie(new Cookie(host, ZimbraCookie.COOKIE_ZM_TRUST_TOKEN, trustedToken, "/", null, false));
        }
        params.setCookiePolicy(state.getCookies().length == 0 ? CookiePolicy.IGNORE_COOKIES : CookiePolicy.BROWSER_COMPATIBILITY);
        params.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(mRetryCount - 1, true));
        params.setSoTimeout(mTimeout);
        params.setVersion(HttpVersion.HTTP_1_1);
        method.setRequestHeader("Connection", mKeepAlive ? "Keep-alive" : "Close");
        if (mHostConfig != null && mHostConfig.getUsername() != null && mHostConfig.getPassword() != null) {
            state.setProxyCredentials(new AuthScope(null, -1), new UsernamePasswordCredentials(mHostConfig.getUsername(), mHostConfig.getPassword()));
        }
        if (mHttpDebugListener != null) {
            mHttpDebugListener.sendSoapMessage(method, soapReq, state);
        }
        int responseCode = mClient.executeMethod(mHostConfig, method, state);
        //   real server issues will probably be "503" or "404"
        if (responseCode != HttpServletResponse.SC_OK && responseCode != HttpServletResponse.SC_INTERNAL_SERVER_ERROR)
            throw ServiceException.PROXY_ERROR(method.getStatusLine().toString(), uri);
        // Read the response body.  Use the stream API instead of the byte[]
        // version to avoid HTTPClient whining about a large response.
        InputStreamReader reader = new InputStreamReader(method.getResponseBodyAsStream(), SoapProtocol.getCharset());
        String responseStr = "";
        try {
            if (respHandler != null) {
                respHandler.process(reader);
                return null;
            } else {
                responseStr = ByteUtil.getContent(reader, (int) method.getResponseContentLength(), false);
                Element soapResp = parseSoapResponse(responseStr, raw);
                if (mHttpDebugListener != null) {
                    mHttpDebugListener.receiveSoapMessage(method, soapResp);
                }
                return soapResp;
            }
        } catch (SoapFaultException x) {
            // attach request/response to the exception and rethrow
            x.setFaultRequest(soapMessage);
            x.setFaultResponse(responseStr.substring(0, Math.min(10240, responseStr.length())));
            throw x;
        }
    } finally {
        // Release the connection to the connection manager
        if (method != null)
            method.releaseConnection();
        // exits.  Leave it here anyway.
        if (!mKeepAlive)
            mClient.getHttpConnectionManager().closeIdleConnections(0);
    }
}
Also used : ZimbraCookie(com.zimbra.common.util.ZimbraCookie) Cookie(org.apache.commons.httpclient.Cookie) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) InputStreamReader(java.io.InputStreamReader) PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpState(org.apache.commons.httpclient.HttpState) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Header(org.apache.commons.httpclient.Header) AuthScope(org.apache.commons.httpclient.auth.AuthScope) HashMap(java.util.HashMap) Map(java.util.Map)

Example 8 with DefaultHttpMethodRetryHandler

use of org.apache.commons.httpclient.DefaultHttpMethodRetryHandler in project opennms by OpenNMS.

the class GoogleGeocoderService method ensureInitialized.

public void ensureInitialized() throws GeocoderException {
    if (m_geocoder == null) {
        final HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
        if (notEmpty(m_clientId) && notEmpty(m_clientKey)) {
            try {
                LOG.info("Initializing Google Geocoder using Client ID and Key.");
                m_geocoder = new AdvancedGeoCoder(httpClient, m_clientId, m_clientKey);
            } catch (final InvalidKeyException e) {
                throw new GeocoderException("Unable to initialize Google Geocoder.", e);
            }
        }
        if (m_geocoder == null) {
            LOG.info("Initializing Google Geocoder using default configuration.");
            m_geocoder = new AdvancedGeoCoder(httpClient);
        }
        /* Configure proxying, if necessary... */
        final String httpProxyHost = System.getProperty("http.proxyHost");
        final Integer httpProxyPort = Integer.getInteger("http.proxyPort");
        if (httpProxyHost != null && httpProxyPort != null) {
            LOG.info("Proxy configuration found, using {}:{} as HTTP proxy.", httpProxyHost, httpProxyPort);
            httpClient.getHostConfiguration().setProxy(httpProxyHost, httpProxyPort);
        } else {
            LOG.info("No proxy configuration found.");
        }
        /* Limit retries... */
        httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(1, true));
        httpClient.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, timeout);
        LOG.info("Google Geocoder initialized.");
    }
}
Also used : HttpClient(org.apache.commons.httpclient.HttpClient) AdvancedGeoCoder(com.google.code.geocoder.AdvancedGeoCoder) MultiThreadedHttpConnectionManager(org.apache.commons.httpclient.MultiThreadedHttpConnectionManager) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) InvalidKeyException(java.security.InvalidKeyException) GeocoderException(org.opennms.features.geocoder.GeocoderException) TemporaryGeocoderException(org.opennms.features.geocoder.TemporaryGeocoderException)

Example 9 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 10 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)

Aggregations

DefaultHttpMethodRetryHandler (org.apache.commons.httpclient.DefaultHttpMethodRetryHandler)18 HttpClient (org.apache.commons.httpclient.HttpClient)13 IOException (java.io.IOException)12 HttpException (org.apache.commons.httpclient.HttpException)11 GetMethod (org.apache.commons.httpclient.methods.GetMethod)7 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 InputStream (java.io.InputStream)3 GZIPInputStream (java.util.zip.GZIPInputStream)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 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