List of usage examples for org.apache.commons.httpclient HttpStatus SC_NO_CONTENT
int SC_NO_CONTENT
To view the source code for org.apache.commons.httpclient HttpStatus SC_NO_CONTENT.
Click Source Link
From source file:org.openhab.action.telegram.internal.Telegram.java
@ActionDoc(text = "Sends a Telegram via Telegram REST API - direct message") static public 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; }// w ww . j ava 2 s .c om String url = String.format(TELEGRAM_URL, groupTokens.get(group).getToken()); HttpClient client = new HttpClient(); PostMethod postMethod = new PostMethod(url); 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()); } catch (IOException e) { logger.error("Fatal transport error: {}", e.toString()); } finally { postMethod.releaseConnection(); } return true; }
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. * /* w w w.jav a2 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 a va2 s .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.opens.tanaguru.util.http.HttpRequestHandler.java
private int computeStatus(int status) { switch (status) { case HttpStatus.SC_FORBIDDEN: case HttpStatus.SC_METHOD_NOT_ALLOWED: case HttpStatus.SC_BAD_REQUEST: case HttpStatus.SC_UNAUTHORIZED: case HttpStatus.SC_PAYMENT_REQUIRED: case HttpStatus.SC_NOT_FOUND: case HttpStatus.SC_NOT_ACCEPTABLE: case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED: case HttpStatus.SC_REQUEST_TIMEOUT: case HttpStatus.SC_CONFLICT: case HttpStatus.SC_GONE: case HttpStatus.SC_LENGTH_REQUIRED: case HttpStatus.SC_PRECONDITION_FAILED: case HttpStatus.SC_REQUEST_TOO_LONG: case HttpStatus.SC_REQUEST_URI_TOO_LONG: case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE: case HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE: case HttpStatus.SC_EXPECTATION_FAILED: case HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE: case HttpStatus.SC_METHOD_FAILURE: case HttpStatus.SC_UNPROCESSABLE_ENTITY: case HttpStatus.SC_LOCKED: case HttpStatus.SC_FAILED_DEPENDENCY: case HttpStatus.SC_INTERNAL_SERVER_ERROR: case HttpStatus.SC_NOT_IMPLEMENTED: case HttpStatus.SC_BAD_GATEWAY: case HttpStatus.SC_SERVICE_UNAVAILABLE: case HttpStatus.SC_GATEWAY_TIMEOUT: case HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED: case HttpStatus.SC_INSUFFICIENT_STORAGE: return 0; case HttpStatus.SC_CONTINUE: case HttpStatus.SC_SWITCHING_PROTOCOLS: case HttpStatus.SC_PROCESSING: case HttpStatus.SC_OK: case HttpStatus.SC_CREATED: case HttpStatus.SC_ACCEPTED: case HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION: case HttpStatus.SC_NO_CONTENT: case HttpStatus.SC_RESET_CONTENT: case HttpStatus.SC_PARTIAL_CONTENT: case HttpStatus.SC_MULTI_STATUS: case HttpStatus.SC_MULTIPLE_CHOICES: case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_MOVED_TEMPORARILY: case HttpStatus.SC_SEE_OTHER: case HttpStatus.SC_NOT_MODIFIED: case HttpStatus.SC_USE_PROXY: case HttpStatus.SC_TEMPORARY_REDIRECT: return 1; default://from w ww. ja v a 2 s. co m return 1; } }
From source file:org.osaf.caldav4j.functional.support.CalDavFixture.java
public void delete(String relativePath) throws IOException { DeleteMethod method = new DeleteMethod(relativePath); //method.setPath(relativePath); executeMethod(HttpStatus.SC_NO_CONTENT, method, false); }
From source file:org.osaf.caldav4j.functional.support.CalDavFixture.java
public void delete(String path, boolean isAbsolutePath) throws IOException { DeleteMethod method = new DeleteMethod(path); //method.setPath(path); executeMethod(HttpStatus.SC_NO_CONTENT, method, false, nullCallback(), isAbsolutePath); }
From source file:org.oscarehr.fax.core.FaxImporter.java
private void deleteFax(DefaultHttpClient client, FaxConfig faxConfig, FaxJob fax) throws ClientProtocolException, IOException { HttpDelete mDelete = new HttpDelete( faxConfig.getUrl() + PATH + "/" + faxConfig.getFaxUser() + "/" + fax.getFile_name()); mDelete.setHeader("accept", "application/json"); mDelete.setHeader("user", faxConfig.getFaxUser()); mDelete.setHeader("passwd", faxConfig.getFaxPasswd()); HttpResponse response = client.execute(mDelete); mDelete.releaseConnection();//from ww w . ja v a2 s . c om if (!(response.getStatusLine().getStatusCode() == HttpStatus.SC_NO_CONTENT)) { throw new ClientProtocolException("CANNOT DELETE " + fax.getFile_name()); } }
From source file:org.socraticgrid.displaycalendarlib.CalendarInit.java
public void delete(String relativePath) throws IOException { DeleteMethod method = new DeleteMethod(); method.setPath(relativePath);//w w w . j av a 2s . c om executeMethod(HttpStatus.SC_NO_CONTENT, method, false); }
From source file:org.sonatype.nexus.proxy.storage.remote.commonshttpclient.CommonsHttpClientRemoteStorage.java
@Override public void storeItem(ProxyRepository repository, StorageItem item) throws UnsupportedStorageOperationException, RemoteStorageException { if (!(item instanceof StorageFileItem)) { throw new UnsupportedStorageOperationException("Storing of non-files remotely is not supported!"); }/*from w w w . j a v a 2 s .c o m*/ StorageFileItem fItem = (StorageFileItem) item; ResourceStoreRequest request = new ResourceStoreRequest(item); URL remoteURL = getAbsoluteUrlFromBase(repository, request); PutMethod method = new PutMethod(remoteURL.toString()); try { method.setRequestEntity( new InputStreamRequestEntity(fItem.getInputStream(), fItem.getLength(), fItem.getMimeType())); int response = executeMethod(repository, request, method, remoteURL); if (response != HttpStatus.SC_OK && response != HttpStatus.SC_CREATED && response != HttpStatus.SC_NO_CONTENT && response != HttpStatus.SC_ACCEPTED) { throw new RemoteStorageException("Unexpected response code while executing " + method.getName() + " method [repositoryId=\"" + repository.getId() + "\", requestPath=\"" + request.getRequestPath() + "\", remoteUrl=\"" + remoteURL.toString() + "\"]. Expected: \"any success (2xx)\". Received: " + response + " : " + HttpStatus.getStatusText(response)); } } catch (IOException e) { throw new RemoteStorageException( e.getMessage() + " [repositoryId=\"" + repository.getId() + "\", requestPath=\"" + request.getRequestPath() + "\", remoteUrl=\"" + remoteURL.toString() + "\"]", e); } finally { method.releaseConnection(); } }
From source file:org.sonatype.nexus.proxy.storage.remote.commonshttpclient.CommonsHttpClientRemoteStorage.java
@Override public void deleteItem(ProxyRepository repository, ResourceStoreRequest request) throws ItemNotFoundException, UnsupportedStorageOperationException, RemoteStorageException { URL remoteURL = getAbsoluteUrlFromBase(repository, request); DeleteMethod method = new DeleteMethod(remoteURL.toString()); try {/*from w ww. java2 s.c om*/ int response = executeMethod(repository, request, method, remoteURL); if (response != HttpStatus.SC_OK && response != HttpStatus.SC_NO_CONTENT && response != HttpStatus.SC_ACCEPTED) { throw new RemoteStorageException("The response to HTTP " + method.getName() + " was unexpected HTTP Code " + response + " : " + HttpStatus.getStatusText(response) + " [repositoryId=\"" + repository.getId() + "\", requestPath=\"" + request.getRequestPath() + "\", remoteUrl=\"" + remoteURL.toString() + "\"]"); } } finally { method.releaseConnection(); } }