Search in sources :

Example 36 with GetMethod

use of org.apache.commons.httpclient.methods.GetMethod 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 37 with GetMethod

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

the class AbstractWeatherProvider method executeRequest.

/**
     * Executes the http request and parses the returned stream.
     */
private void executeRequest(Weather weather, String url, LocationConfig locationConfig) throws Exception {
    GetMethod get = null;
    try {
        logger.trace("{}[{}]: request : {}", getProviderName(), locationConfig.getLocationId(), url);
        get = new GetMethod(url);
        httpClient.executeMethod(get);
        InputStream is = null;
        if (logger.isTraceEnabled()) {
            String response = get.getResponseBodyAsString(100000);
            response = StringUtils.remove(response, "\n");
            response = StringUtils.trim(response);
            logger.trace("{}[{}]: response: {}", getProviderName(), locationConfig.getLocationId(), response);
            is = new ByteArrayInputStream(response.getBytes(get.getResponseCharSet()));
        } else {
            is = get.getResponseBodyAsStream();
        }
        if (get.getStatusCode() == HttpStatus.SC_OK) {
            parser.parseInto(is, weather);
        }
        // special handling because of bad OpenWeatherMap json structure
        if (weather.getProvider() == ProviderName.OPENWEATHERMAP && weather.getResponseCode() != null && weather.getResponseCode() == 200) {
            weather.setError(null);
        }
        if (!weather.hasError() && get.getStatusCode() != HttpStatus.SC_OK) {
            weather.setError(get.getStatusLine().toString());
        }
        if (weather.hasError()) {
            logger.error("{}[{}]: Can't retreive weather data: {}", getProviderName(), locationConfig.getLocationId(), weather.getError());
        } else {
            setLastUpdate(weather);
        }
    } catch (Exception ex) {
        logger.error(getProviderName() + ": " + ex.getMessage());
        weather.setError(ex.getClass().getSimpleName() + ": " + ex.getMessage());
        throw ex;
    } finally {
        if (get != null) {
            get.releaseConnection();
        }
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) GetMethod(org.apache.commons.httpclient.methods.GetMethod)

Example 38 with GetMethod

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

the class HttpClient method get.

public Response get(String url, PostParameter[] params) throws WeiboException {
    log("Request:");
    log("GET:" + url);
    if (null != params && params.length > 0) {
        String encodedParams = HttpClient.encodeParameters(params);
        if (-1 == url.indexOf("?")) {
            url += "?" + encodedParams;
        } else {
            url += "&" + encodedParams;
        }
    }
    GetMethod getmethod = new GetMethod(url);
    return httpRequest(getmethod);
}
Also used : GetMethod(org.apache.commons.httpclient.methods.GetMethod)

Example 39 with GetMethod

use of org.apache.commons.httpclient.methods.GetMethod in project camel by apache.

the class UndertowMethodRestricTest method testImproperHttpMethod.

@Test
public void testImproperHttpMethod() throws Exception {
    HttpClient httpClient = new HttpClient();
    GetMethod httpGet = new GetMethod(url);
    int status = httpClient.executeMethod(httpGet);
    assertEquals("Get a wrong response status", 405, status);
}
Also used : HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) Test(org.junit.Test)

Example 40 with GetMethod

use of org.apache.commons.httpclient.methods.GetMethod in project camel by apache.

the class NettyHttpMethodRestrictTest method testImproperHttpMethod.

@Test
public void testImproperHttpMethod() throws Exception {
    HttpClient httpClient = new HttpClient();
    GetMethod httpGet = new GetMethod(getUrl());
    int status = httpClient.executeMethod(httpGet);
    assertEquals("Get a wrong response status", 405, status);
}
Also used : HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) Test(org.junit.Test)

Aggregations

GetMethod (org.apache.commons.httpclient.methods.GetMethod)357 HttpClient (org.apache.commons.httpclient.HttpClient)216 HttpMethod (org.apache.commons.httpclient.HttpMethod)93 IOException (java.io.IOException)82 Test (org.junit.Test)70 InputStream (java.io.InputStream)65 HttpException (org.apache.commons.httpclient.HttpException)41 Map (java.util.Map)39 ArrayList (java.util.ArrayList)37 HashMap (java.util.HashMap)36 JSONParser (org.json.simple.parser.JSONParser)34 JSONObject (org.json.simple.JSONObject)31 Header (org.apache.commons.httpclient.Header)22 Element (org.w3c.dom.Element)22 PostMethod (org.apache.commons.httpclient.methods.PostMethod)21 TypeToken (com.google.gson.reflect.TypeToken)20 List (java.util.List)19 HttpState (org.apache.commons.httpclient.HttpState)18 URI (java.net.URI)17 JSONArray (org.json.simple.JSONArray)17