Search in sources :

Example 6 with HttpMethod

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

the class HttpMethodBaseExecuteMethodInterceptor method setHttpSampledHeader.

private void setHttpSampledHeader(final Object target) {
    if (isDebug) {
        logger.debug("set Sampling flag=false");
    }
    if (target instanceof HttpMethod) {
        final HttpMethod httpMethod = (HttpMethod) target;
        httpMethod.setRequestHeader(Header.HTTP_SAMPLED.toString(), SamplingFlagUtils.SAMPLING_RATE_FALSE);
    }
}
Also used : HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 7 with HttpMethod

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

the class FrontierSiliconRadioConnection method doLogin.

/**
     * Perform login/establish a new session. Uses the PIN number and when successful saves the assigned sessionID for
     * future requests.
     * 
     * @return <code>true</code> if login was successful; <code>false</code> otherwise.
     */
public boolean doLogin() {
    // reset login flag
    isLoggedIn = false;
    if (httpClient == null) {
        httpClient = new HttpClient();
    }
    final String url = "http://" + hostname + ":" + port + "/fsapi/CREATE_SESSION?pin=" + pin;
    logger.trace("opening URL:" + url);
    final HttpMethod method = new GetMethod(url);
    method.getParams().setSoTimeout(SOCKET_TIMEOUT);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
    try {
        final int statusCode = httpClient.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            logger.warn("Method failed: " + method.getStatusLine());
        }
        final String responseBody = IOUtils.toString(method.getResponseBodyAsStream());
        if (!responseBody.isEmpty()) {
            logger.trace("login response: " + responseBody);
        }
        try {
            final FrontierSiliconRadioApiResult result = new FrontierSiliconRadioApiResult(responseBody);
            if (result.isStatusOk()) {
                logger.trace("login successful");
                sessionId = result.getSessionId();
                isLoggedIn = true;
                // login successful :-)
                return true;
            }
        } catch (Exception e) {
            logger.error("Parsing response failed");
        }
    } catch (HttpException he) {
        logger.error("Fatal protocol violation: {}", he.toString());
    } catch (IOException ioe) {
        logger.error("Fatal transport error: {}", ioe.toString());
    } finally {
        method.releaseConnection();
    }
    // login not successful
    return false;
}
Also used : HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException) HttpMethod(org.apache.commons.httpclient.HttpMethod) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException)

Example 8 with HttpMethod

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

the class FrontierSiliconRadioConnection method doRequest.

/**
     * Performs a request to the radio with addition parameters.
     * 
     * Typically used for changing parameters.
     * 
     * @param REST
     *            API requestString, e.g. "SET/netRemote.sys.power"
     * @param params
     *            , e.g. "value=1"
     * @return request result
     */
public FrontierSiliconRadioApiResult doRequest(String requestString, String params) {
    // 3 retries upon failure
    for (int i = 0; i < 3; i++) {
        if (!isLoggedIn && !doLogin()) {
            // not logged in and login was not successful - try again!
            continue;
        }
        final String url = "http://" + hostname + ":" + port + "/fsapi/" + requestString + "?pin=" + pin + "&sid=" + sessionId + (params == null || params.trim().length() == 0 ? "" : "&" + params);
        logger.trace("calling url: '" + url + "'");
        final HttpMethod method = new GetMethod(url);
        method.getParams().setSoTimeout(SOCKET_TIMEOUT);
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
        try {
            final int statusCode = httpClient.executeMethod(method);
            if (statusCode != HttpStatus.SC_OK) {
                logger.warn("Method failed: " + method.getStatusLine());
                isLoggedIn = false;
                method.releaseConnection();
                continue;
            }
            final String responseBody = IOUtils.toString(method.getResponseBodyAsStream());
            if (!responseBody.isEmpty()) {
                logger.trace("got result: " + responseBody);
            } else {
                logger.debug("got empty result");
                isLoggedIn = false;
                method.releaseConnection();
                continue;
            }
            final FrontierSiliconRadioApiResult result = new FrontierSiliconRadioApiResult(responseBody);
            if (result.isStatusOk()) {
                return result;
            }
            isLoggedIn = false;
            method.releaseConnection();
            // try again
            continue;
        } catch (HttpException he) {
            logger.error("Fatal protocol violation: {}", he.toString());
            isLoggedIn = false;
        } catch (IOException ioe) {
            logger.error("Fatal transport error: {}", ioe.toString());
        } finally {
            method.releaseConnection();
        }
    }
    // 3 tries failed. log in again next time, maybe our session went invalid (radio restarted?)
    isLoggedIn = false;
    return null;
}
Also used : GetMethod(org.apache.commons.httpclient.methods.GetMethod) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 9 with HttpMethod

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

use of org.apache.commons.httpclient.HttpMethod in project camel by apache.

the class NettyHttpHeaderMaxSizeTest method testHttpHeaderMaxSizeOk.

@Test
public void testHttpHeaderMaxSizeOk() throws Exception {
    HttpClient client = new HttpClient();
    HttpMethod method = new PostMethod("http://localhost:" + getPort() + "/myapp/mytest");
    method.setRequestHeader("name", "you");
    client.executeMethod(method);
    assertEquals(200, method.getStatusCode());
    assertEquals("Bye World", method.getResponseBodyAsString());
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpClient(org.apache.commons.httpclient.HttpClient) HttpMethod(org.apache.commons.httpclient.HttpMethod) Test(org.junit.Test)

Aggregations

HttpMethod (org.apache.commons.httpclient.HttpMethod)151 HttpClient (org.apache.commons.httpclient.HttpClient)99 GetMethod (org.apache.commons.httpclient.methods.GetMethod)95 InputStream (java.io.InputStream)61 IOException (java.io.IOException)43 ArrayList (java.util.ArrayList)30 HttpException (org.apache.commons.httpclient.HttpException)28 Map (java.util.Map)24 Test (org.junit.Test)23 Element (org.w3c.dom.Element)22 HashMap (java.util.HashMap)20 PostMethod (org.apache.commons.httpclient.methods.PostMethod)19 Header (org.apache.commons.httpclient.Header)17 List (java.util.List)14 NameValuePair (org.apache.commons.httpclient.NameValuePair)13 NodeList (org.w3c.dom.NodeList)12 FileInputStream (java.io.FileInputStream)10 HttpTest (org.apache.sling.commons.testing.integration.HttpTest)10 SAXBuilder (org.jdom.input.SAXBuilder)10 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)9