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;
}
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;
}
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;
}
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);
}
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;
}
}
Aggregations