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;
}
use of org.apache.commons.httpclient.DefaultHttpMethodRetryHandler in project hadoop by apache.
the class SwiftRestClient method perform.
/**
* Performs the HTTP request, validates the response code and returns
* the received data. HTTP Status codes are converted into exceptions.
* @param reason why is this operation taking place. Used for statistics
* @param uri URI to source
* @param processor HttpMethodProcessor
* @param <M> method
* @param <R> result type
* @return result of HTTP request
* @throws IOException IO problems
* @throws SwiftBadRequestException the status code indicated "Bad request"
* @throws SwiftInvalidResponseException the status code is out of range
* for the action (excluding 404 responses)
* @throws SwiftInternalStateException the internal state of this client
* is invalid
* @throws FileNotFoundException a 404 response was returned
*/
private <M extends HttpMethod, R> R perform(String reason, URI uri, HttpMethodProcessor<M, R> processor) throws IOException, SwiftBadRequestException, SwiftInternalStateException, SwiftInvalidResponseException, FileNotFoundException {
checkNotNull(uri);
checkNotNull(processor);
final M method = processor.createMethod(uri.toString());
//retry policy
HttpMethodParams methodParams = method.getParams();
methodParams.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(retryCount, false));
methodParams.setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, connectTimeout);
methodParams.setSoTimeout(socketTimeout);
method.addRequestHeader(HEADER_USER_AGENT, SWIFT_USER_AGENT);
Duration duration = new Duration();
boolean success = false;
try {
int statusCode = 0;
try {
statusCode = exec(method);
} catch (IOException e) {
//rethrow with extra diagnostics and wiki links
throw ExceptionDiags.wrapException(uri.toString(), method.getName(), e);
}
//look at the response and see if it was valid or not.
//Valid is more than a simple 200; even 404 "not found" is considered
//valid -which it is for many methods.
//validate the allowed status code for this operation
int[] allowedStatusCodes = processor.getAllowedStatusCodes();
boolean validResponse = isStatusCodeExpected(statusCode, allowedStatusCodes);
if (!validResponse) {
IOException ioe = buildException(uri, method, statusCode);
throw ioe;
}
R r = processor.extractResult(method);
success = true;
return r;
} catch (IOException e) {
//release the connection -always
method.releaseConnection();
throw e;
} finally {
duration.finished();
durationStats.add(method.getName() + " " + reason, duration, success);
}
}
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();
}
}
use of org.apache.commons.httpclient.DefaultHttpMethodRetryHandler in project pinpoint by naver.
the class HttpClientIT method hostConfig.
@Test
public void hostConfig() throws Exception {
HttpClient client = new HttpClient();
client.getParams().setConnectionManagerTimeout(CONNECTION_TIMEOUT);
client.getParams().setSoTimeout(SO_TIMEOUT);
HostConfiguration config = new HostConfiguration();
config.setHost("weather.naver.com", 80, "http");
GetMethod method = new GetMethod("/rgn/cityWetrMain.nhn");
// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
method.setQueryString(new NameValuePair[] { new NameValuePair("key2", "value2") });
try {
// Execute the method.
client.executeMethod(config, method);
} catch (Exception ignored) {
} finally {
method.releaseConnection();
}
PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
verifier.printCache();
}
use of org.apache.commons.httpclient.DefaultHttpMethodRetryHandler in project zaproxy by zaproxy.
the class HttpSender method setMaxRetriesOnIOError.
/**
* Sets the maximum number of retries of an unsuccessful request caused by I/O errors.
* <p>
* The default number of retries is 3.
*
* @param retries the number of retries
* @throws IllegalArgumentException if {@code retries} is negative.
* @since 2.4.0
*/
public void setMaxRetriesOnIOError(int retries) {
if (retries < 0) {
throw new IllegalArgumentException("Parameter retries must be greater or equal to zero.");
}
HttpMethodRetryHandler retryHandler = new DefaultHttpMethodRetryHandler(retries, false);
client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler);
clientViaProxy.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler);
}
Aggregations