Search in sources :

Example 1 with HeaderElement

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

the class AbstractRequest method executeUrl.

/**
     * Executes the given <code>url</code> with the given <code>httpMethod</code>. In the case of httpMethods that do
     * not support automatic redirection, manually handle the HTTP temporary redirect (307) and retry with the new URL.
     * 
     * @param httpMethod
     *            the HTTP method to use
     * @param url
     *            the url to execute (in milliseconds)
     * @param contentString
     *            the content to be sent to the given <code>url</code> or <code>null</code> if no content should be
     *            sent.
     * @param contentType
     *            the content type of the given <code>contentString</code>
     * @return the response body or <code>NULL</code> when the request went wrong
     */
protected final String executeUrl(final String httpMethod, final String url, final String contentString, final String contentType) {
    HttpClient client = new HttpClient();
    HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url);
    method.getParams().setSoTimeout(httpRequestTimeout);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
    for (String httpHeaderKey : HTTP_HEADERS.stringPropertyNames()) {
        method.addRequestHeader(new Header(httpHeaderKey, HTTP_HEADERS.getProperty(httpHeaderKey)));
    }
    // add content if a valid method is given ...
    if (method instanceof EntityEnclosingMethod && contentString != null) {
        EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method;
        InputStream content = new ByteArrayInputStream(contentString.getBytes());
        eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType));
    }
    if (logger.isDebugEnabled()) {
        try {
            logger.trace("About to execute '" + method.getURI().toString() + "'");
        } catch (URIException e) {
            logger.trace(e.getMessage());
        }
    }
    try {
        int statusCode = client.executeMethod(method);
        if (statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_ACCEPTED) {
            // perfectly fine but we cannot expect any answer...
            return null;
        }
        // Manually handle 307 redirects with a little tail recursion
        if (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) {
            Header[] headers = method.getResponseHeaders("Location");
            String newUrl = headers[headers.length - 1].getValue();
            return executeUrl(httpMethod, newUrl, contentString, contentType);
        }
        if (statusCode != HttpStatus.SC_OK) {
            logger.warn("Method failed: " + method.getStatusLine());
        }
        InputStream tmpResponseStream = method.getResponseBodyAsStream();
        Header encodingHeader = method.getResponseHeader("Content-Encoding");
        if (encodingHeader != null) {
            for (HeaderElement ehElem : encodingHeader.getElements()) {
                if (ehElem.toString().matches(".*gzip.*")) {
                    tmpResponseStream = new GZIPInputStream(tmpResponseStream);
                    logger.trace("GZipped InputStream from {}", url);
                } else if (ehElem.toString().matches(".*deflate.*")) {
                    tmpResponseStream = new InflaterInputStream(tmpResponseStream);
                    logger.trace("Deflated InputStream from {}", url);
                }
            }
        }
        String responseBody = IOUtils.toString(tmpResponseStream);
        if (!responseBody.isEmpty()) {
            logger.trace(responseBody);
        }
        return responseBody;
    } catch (HttpException he) {
        logger.error("Fatal protocol violation: {}", he.toString());
    } catch (IOException ioe) {
        logger.error("Fatal transport error: {}", ioe.toString());
    } finally {
        method.releaseConnection();
    }
    return null;
}
Also used : InputStreamRequestEntity(org.apache.commons.httpclient.methods.InputStreamRequestEntity) GZIPInputStream(java.util.zip.GZIPInputStream) InflaterInputStream(java.util.zip.InflaterInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) HeaderElement(org.apache.commons.httpclient.HeaderElement) InflaterInputStream(java.util.zip.InflaterInputStream) EntityEnclosingMethod(org.apache.commons.httpclient.methods.EntityEnclosingMethod) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) IOException(java.io.IOException) GZIPInputStream(java.util.zip.GZIPInputStream) URIException(org.apache.commons.httpclient.URIException) Header(org.apache.commons.httpclient.Header) ByteArrayInputStream(java.io.ByteArrayInputStream) HttpClient(org.apache.commons.httpclient.HttpClient) HttpException(org.apache.commons.httpclient.HttpException) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 2 with HeaderElement

use of org.apache.commons.httpclient.HeaderElement in project ecf by eclipse.

the class SimpleResponse method getCharset.

public String getCharset() {
    String charset = DEFAULT_CONTENT_CHARSET;
    Header contenttype = this.headers.getFirstHeader("Content-Type");
    if (contenttype != null) {
        HeaderElement[] values = contenttype.getElements();
        if (values.length == 1) {
            NameValuePair param = values[0].getParameterByName("charset");
            if (param != null) {
                charset = param.getValue();
            }
        }
    }
    return charset;
}
Also used : NameValuePair(org.apache.commons.httpclient.NameValuePair) Header(org.apache.commons.httpclient.Header) HeaderElement(org.apache.commons.httpclient.HeaderElement)

Example 3 with HeaderElement

use of org.apache.commons.httpclient.HeaderElement 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 4 with HeaderElement

use of org.apache.commons.httpclient.HeaderElement in project intellij-community by JetBrains.

the class TaskResponseUtil method getResponseContentAsReader.

public static Reader getResponseContentAsReader(@NotNull HttpMethod response) throws IOException {
    //if (!response.hasBeenUsed()) {
    //  return new StringReader("");
    //}
    InputStream stream = response.getResponseBodyAsStream();
    String charsetName = null;
    org.apache.commons.httpclient.Header header = response.getResponseHeader(HTTP.CONTENT_TYPE);
    if (header != null) {
        // find out encoding
        for (HeaderElement part : header.getElements()) {
            NameValuePair pair = part.getParameterByName("charset");
            if (pair != null) {
                charsetName = pair.getValue();
            }
        }
    }
    return new InputStreamReader(stream, charsetName == null ? DEFAULT_CHARSET_NAME : charsetName);
}
Also used : NameValuePair(org.apache.commons.httpclient.NameValuePair) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) HeaderElement(org.apache.commons.httpclient.HeaderElement)

Example 5 with HeaderElement

use of org.apache.commons.httpclient.HeaderElement in project ecf by eclipse.

the class SimpleRequest method getCharset.

public String getCharset() {
    String charset = null;
    Header contenttype = this.headers.getFirstHeader("Content-Type");
    if (contenttype != null) {
        HeaderElement[] values = contenttype.getElements();
        if (values.length == 1) {
            NameValuePair param = values[0].getParameterByName("charset");
            if (param != null) {
                charset = param.getValue();
            }
        }
    }
    if (charset != null) {
        return charset;
    } else {
        return DEFAULT_CONTENT_CHARSET;
    }
}
Also used : NameValuePair(org.apache.commons.httpclient.NameValuePair) Header(org.apache.commons.httpclient.Header) HeaderElement(org.apache.commons.httpclient.HeaderElement)

Aggregations

HeaderElement (org.apache.commons.httpclient.HeaderElement)5 Header (org.apache.commons.httpclient.Header)4 NameValuePair (org.apache.commons.httpclient.NameValuePair)4 InputStream (java.io.InputStream)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 IOException (java.io.IOException)2 GZIPInputStream (java.util.zip.GZIPInputStream)2 InflaterInputStream (java.util.zip.InflaterInputStream)2 DefaultHttpMethodRetryHandler (org.apache.commons.httpclient.DefaultHttpMethodRetryHandler)2 HttpClient (org.apache.commons.httpclient.HttpClient)2 HttpException (org.apache.commons.httpclient.HttpException)2 InputStreamReader (java.io.InputStreamReader)1 ImageInputStream (javax.imageio.stream.ImageInputStream)1 HttpMethod (org.apache.commons.httpclient.HttpMethod)1 URIException (org.apache.commons.httpclient.URIException)1 EntityEnclosingMethod (org.apache.commons.httpclient.methods.EntityEnclosingMethod)1 InputStreamRequestEntity (org.apache.commons.httpclient.methods.InputStreamRequestEntity)1 PostMethod (org.apache.commons.httpclient.methods.PostMethod)1 ActionDoc (org.openhab.core.scriptengine.action.ActionDoc)1