List of usage examples for org.apache.commons.httpclient.params HttpMethodParams RETRY_HANDLER
String RETRY_HANDLER
To view the source code for org.apache.commons.httpclient.params HttpMethodParams RETRY_HANDLER.
Click Source Link
From source file:org.openhab.binding.frontiersiliconradio.internal.FrontierSiliconRadioConnection.java
/** * Perform login/establish a new session. Uses the PIN number and when successful saves the assigned sessionID for * future requests.//from ww w . j a v a 2 s .c o m * * @return <code>true</code> if login was successful; <code>false</code> otherwise. */ public boolean doLogin() { isLoggedIn = false; // reset login flag 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; return true; // login successful :-) } } 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(); } return false; // login not successful }
From source file:org.openhab.binding.frontiersiliconradio.internal.FrontierSiliconRadioConnection.java
/** * Performs a request to the radio with addition parameters. * //from w w w . j a va 2 s . c o m * 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()) { continue; // not logged in and login was not successful - try again! } 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(); continue; // try again } 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(); } } isLoggedIn = false; // 3 tries failed. log in again next time, maybe our session went invalid (radio restarted?) return null; }
From source file:org.openhab.binding.garadget.internal.Connection.java
/** * Send a command to the Particle REST API (convenience function). * * @param device/* w w w . j a va2s.c o m*/ * the device context, or <code>null</code> if not needed for this command. * @param funcName * the function name to call, or variable/field to retrieve if <code>command</code> is * <code>null</code>. * @param user * the user name to use in Basic Authentication if the funcName would require Basic Authentication. * @param pass * the password to use in Basic Authentication if the funcName would require Basic Authentication. * @param command * the command to send to the API. * @param proc * a callback object that receives the status code and response body, or <code>null</code> if not * needed. */ public void sendCommand(AbstractDevice device, String funcName, String user, String pass, String command, HttpResponseHandler proc) { String url = null; String httpMethod = null; String content = null; String contentType = null; Properties headers = new Properties(); logger.trace("sendCommand: funcName={}", funcName); switch (funcName) { case "createToken": httpMethod = HTTP_POST; url = TOKEN_URL; content = command; contentType = APPLICATION_FORM_URLENCODED; break; case "deleteToken": httpMethod = HTTP_DELETE; url = String.format(ACCESS_TOKENS_URL, tokens.accessToken); break; case "getDevices": httpMethod = HTTP_GET; url = String.format(GET_DEVICES_URL, tokens.accessToken); break; default: url = String.format(DEVICE_FUNC_URL, device.getId(), funcName, tokens.accessToken); if (command == null) { // retrieve a variable httpMethod = HTTP_GET; } else { // call a function httpMethod = HTTP_POST; content = command; contentType = APPLICATION_JSON; } break; } HttpClient client = new HttpClient(); // Only perform basic authentication when we aren't using OAuth if (!url.contains("access_token=")) { Credentials credentials = new UsernamePasswordCredentials(user, pass); client.getParams().setAuthenticationPreemptive(true); client.getState().setCredentials(AuthScope.ANY, credentials); } HttpMethod method = createHttpMethod(httpMethod, url); method.getParams().setSoTimeout(timeout); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); for (String httpHeaderKey : headers.stringPropertyNames()) { method.addRequestHeader(new Header(httpHeaderKey, headers.getProperty(httpHeaderKey))); logger.trace("Header key={}, value={}", httpHeaderKey, headers.getProperty(httpHeaderKey)); } try { // add content if a valid method is given ... if (method instanceof EntityEnclosingMethod && content != null) { EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method; eeMethod.setRequestEntity(new StringRequestEntity(content, contentType, null)); logger.trace("content='{}', contentType='{}'", content, contentType); } if (logger.isDebugEnabled()) { try { logger.debug("About to execute '{}'", method.getURI()); } catch (URIException e) { logger.debug(e.getMessage()); } } int statusCode = client.executeMethod(method); if (statusCode >= HttpStatus.SC_BAD_REQUEST) { logger.debug("Method failed: " + method.getStatusLine()); } String responseBody = IOUtils.toString(method.getResponseBodyAsStream()); if (!responseBody.isEmpty()) { logger.debug("Body of response: {}", responseBody); } if (proc != null) { proc.handleResponse(statusCode, responseBody); } } catch (HttpException he) { logger.warn("{}", he); } catch (IOException ioe) { logger.debug("{}", ioe); } finally { method.releaseConnection(); } }
From source file:org.openhab.binding.km200.internal.KM200Comm.java
/** * This function does the GET http communication to the device * */// w ww .j av a2s .c o m public byte[] getDataFromService(String service) { byte[] responseBodyB64 = null; int maxNbrGets = 3; int statusCode = 0; // Create an instance of HttpClient. if (client == null) { client = new HttpClient(); } synchronized (client) { // Create a method instance. GetMethod method = new GetMethod("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"); try { for (int i = 0; i < maxNbrGets && statusCode != HttpStatus.SC_OK; i++) { // Execute the method. statusCode = client.executeMethod(method); // Check the status switch (statusCode) { case HttpStatus.SC_OK: break; case HttpStatus.SC_INTERNAL_SERVER_ERROR: /* Unknown problem with the device, wait and try again */ logger.warn("HTTP GET failed: 500, internal server error, repeating.. "); Thread.sleep(2000L); continue; case HttpStatus.SC_FORBIDDEN: /* Service is available but not readable */ byte[] test = new byte[1]; return test; default: logger.error("HTTP GET failed: {}", method.getStatusLine()); return null; } } device.setCharSet(method.getResponseCharSet()); // Read the response body. responseBodyB64 = ByteStreams.toByteArray(method.getResponseBodyAsStream()); } catch (HttpException e) { logger.error("Fatal protocol violation: {}", e.getMessage()); } catch (InterruptedException e) { logger.error("Sleep was interrupted: {}", e.getMessage()); } catch (IOException e) { logger.error("Fatal transport error: {}", e.getMessage()); } finally { // Release the connection. method.releaseConnection(); } return responseBodyB64; } }
From source file:org.openhab.binding.km200.internal.KM200Comm.java
/** * This function does the SEND http communication to the device * *//*from w w w .ja v a2 s. c om*/ 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; } }
From source file:org.openhab.binding.nest.internal.messages.AbstractRequest.java
/** * 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. * //from w w w . j a va 2 s . c o m * @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(HTTP_REQUEST_TIMEOUT); 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; }
From source file:org.openhab.io.net.http.HttpUtil.java
/** * Executes the given <code>url</code> with the given <code>httpMethod</code> * /*from w ww. j av a 2s . c o m*/ * @param httpMethod the HTTP method to use * @param url the url to execute (in milliseconds) * @param httpHeaders optional HTTP headers which has to be set on request * @param content the content to be send to the given <code>url</code> or * <code>null</code> if no content should be send. * @param contentType the content type of the given <code>content</code> * @param timeout the socket timeout to wait for data * @param proxyHost the hostname of the proxy * @param proxyPort the port of the proxy * @param proxyUser the username to authenticate with the proxy * @param proxyPassword the password to authenticate with the proxy * @param nonProxyHosts the hosts that won't be routed through the proxy * @return the response body or <code>NULL</code> when the request went wrong */ public static String executeUrl(String httpMethod, String url, Properties httpHeaders, InputStream content, String contentType, int timeout, String proxyHost, Integer proxyPort, String proxyUser, String proxyPassword, String nonProxyHosts) { HttpClient client = new HttpClient(); // only configure a proxy if a host is provided if (StringUtils.isNotBlank(proxyHost) && proxyPort != null && shouldUseProxy(url, nonProxyHosts)) { client.getHostConfiguration().setProxy(proxyHost, proxyPort); if (StringUtils.isNotBlank(proxyUser)) { client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxyUser, proxyPassword)); } } HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url); method.getParams().setSoTimeout(timeout); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); if (httpHeaders != null) { for (String httpHeaderKey : httpHeaders.stringPropertyNames()) { method.addRequestHeader(new Header(httpHeaderKey, httpHeaders.getProperty(httpHeaderKey))); } } // add content if a valid method is given ... if (method instanceof EntityEnclosingMethod && content != null) { EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method; eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType)); } Credentials credentials = extractCredentials(url); if (credentials != null) { client.getParams().setAuthenticationPreemptive(true); client.getState().setCredentials(AuthScope.ANY, credentials); } if (logger.isDebugEnabled()) { try { logger.debug("About to execute '" + method.getURI().toString() + "'"); } catch (URIException e) { logger.debug(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; } 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.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); } 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; }
From source file:org.opennms.features.geocoder.google.GoogleGeocoderService.java
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); }// www .ja v a2 s . co m } 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)); LOG.info("Google Geocoder initialized."); } }
From source file:org.openo.nfvo.monitor.dac.util.APIHttpClient.java
public static String doGet(String url, String queryString, String charset, String token) { HttpClient httpClient = new HttpClient(); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000); GetMethod getMethod = new GetMethod(url); if (!Global.isEmpty(queryString)) { getMethod.setQueryString(queryString); }/*from w w w.ja v a 2 s . c o m*/ getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 10000); if (!Global.isEmpty(token)) { getMethod.addRequestHeader("X-Auth-Token", token); } getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); String response = ""; try { int statusCode = httpClient.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) { logger.error("request error: " + getMethod.getStatusLine()); } byte[] responseBody = getMethod.getResponseBody(); response = new String(responseBody, charset); logger.debug("----------response:" + response); } catch (HttpException e) { logger.error("Exception", e); } catch (IOException e) { logger.error("Exception", e); } finally { getMethod.releaseConnection(); } return response; }
From source file:org.openo.nfvo.monitor.umc.util.APIHttpClient.java
public static String doGet(String url, String queryString, String charset, String token) { HttpClient httpClient = new HttpClient(); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000); GetMethod getMethod = new GetMethod(url); if (!Global.isEmpty(queryString)) { getMethod.setQueryString(queryString); }/*www.j a v a 2 s . c o m*/ getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 10000); if (!Global.isEmpty(token)) { getMethod.addRequestHeader("X-Auth-Token", token); } getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); String response = ""; try { int statusCode = httpClient.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) { logger.error("request error: " + getMethod.getStatusLine()); } else { byte[] responseBody = getMethod.getResponseBody(); response = new String(responseBody, charset); logger.debug("----------response:" + response); } } catch (HttpException e) { logger.error("Exception", e); } catch (IOException e) { logger.error("Exception", e); } finally { getMethod.releaseConnection(); } return response; }