/** {@inheritDoc} */ public boolean exists() throws ResourceException { HeadMethod headMethod = new HeadMethod(resourceUrl); headMethod.addRequestHeader("Connection", "close"); try { httpClient.executeMethod(headMethod); if (headMethod.getStatusCode() != HttpStatus.SC_OK) { return false; } return true; } catch (IOException e) { throw new ResourceException("Unable to contact resource URL: " + resourceUrl, e); } finally { headMethod.releaseConnection(); } }
private static boolean pageExists(@NotNull String url) { if (new File(url).exists()) { return true; } final HttpClient client = new HttpClient(); final HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams(); params.setSoTimeout(5 * 1000); params.setConnectionTimeout(5 * 1000); try { final HeadMethod method = new HeadMethod(url); final int rc = client.executeMethod(method); if (rc == 404) { return false; } } catch (IllegalArgumentException e) { return false; } catch (IOException ignored) { } return true; }
public void testExecuteMethod() { OwnCloudClient client = new OwnCloudClient(mServerUri, NetworkUtils.getMultiThreadedConnManager()); HeadMethod head = new HeadMethod(client.getWebdavUri() + "/"); int status = -1; try { status = client.executeMethod(head); assertTrue("Wrong status code returned: " + status, status > 99 && status < 600); } catch (IOException e) { Log.e(TAG, "Exception in HEAD method execution", e); // TODO - make it fail? ; try several times, and make it fail if none // is right? } finally { head.releaseConnection(); } }
public static void main(String[] args) throws Exception { String message = "Hello Ivy!"; System.out.println("standard message : " + message); System.out.println("capitalized by " + WordUtils.class.getName() + " : " + WordUtils.capitalizeFully(message)); HttpClient client = new HttpClient(); HeadMethod head = new HeadMethod("http://www.ibiblio.org/"); client.executeMethod(head); int status = head.getStatusCode(); System.out.println("head status code with httpclient: " + status); head.releaseConnection(); System.out.println( "now check if httpclient dependency on commons-logging has been realized"); Class<?> clss = Class.forName("org.apache.commons.logging.Log"); System.out.println("found logging class in classpath: " + clss); }
public boolean exists(String filename) throws FileResourceException { HeadMethod m = new HeadMethod(contact + '/' + filename); try { int code = client.executeMethod(m); try { if (code != HttpStatus.SC_OK) { return false; } else { return true; } } finally { m.releaseConnection(); } } catch (Exception e) { throw new FileResourceException(e); } }
/** * Determines the type of this file. Must not return null. The return * value of this method is cached, so the implementation can be expensive. */ @Override protected FileType doGetType() throws Exception { // Use the HEAD method to probe the file. method = new HeadMethod(); setupMethod(method); final HttpClient client = fileSystem.getClient(); final int status = client.executeMethod(method); method.releaseConnection(); if (status == HttpURLConnection.HTTP_OK) { return FileType.FILE; } else if (status == HttpURLConnection.HTTP_NOT_FOUND || status == HttpURLConnection.HTTP_GONE) { return FileType.IMAGINARY; } else { throw new FileSystemException("vfs.provider.http/head.error", getName()); } }
/** * Create a Commons HttpMethodBase object for the given HTTP method * and URI specification. * @param httpMethod the HTTP method * @param uri the URI * @return the Commons HttpMethodBase object */ protected HttpMethodBase createCommonsHttpMethod(HttpMethod httpMethod, String uri) { switch (httpMethod) { case GET: return new GetMethod(uri); case DELETE: return new DeleteMethod(uri); case HEAD: return new HeadMethod(uri); case OPTIONS: return new OptionsMethod(uri); case POST: return new PostMethod(uri); case PUT: return new PutMethod(uri); case TRACE: return new TraceMethod(uri); case PATCH: throw new IllegalArgumentException( "HTTP method PATCH not available before Apache HttpComponents HttpClient 4.2"); default: throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod); } }
public static void checkUrlExistence(String url) { if (url.toLowerCase().startsWith("http") || url.toLowerCase().startsWith("https")) { HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager()); HeadMethod httphead = new HeadMethod(url); try { if (httpClient.executeMethod(httphead) != HttpStatus.SC_OK) { throw new IllegalArgumentException("Invalid URL: " + url); } if (url.endsWith("metalink") && !checkUrlExistenceMetalink(url)) { throw new IllegalArgumentException("Invalid URLs defined on metalink: " + url); } } catch (HttpException hte) { throw new IllegalArgumentException("Cannot reach URL: " + url); } catch (IOException ioe) { throw new IllegalArgumentException("Cannot reach URL: " + url); } } }
@Test public void testHeadObject() throws Exception { // create bucket and store object assertEquals("OK", conn.createBucket(bucketName, null, null).connection.getResponseMessage()); S3Object object = new S3Object(testData.getBytes(), null); assertEquals("OK", conn.put(bucketName, objectName, object, null).connection.getResponseMessage()); // grant public read access to the bucket Map<String, List<String>> headers = new HashMap<String, List<String>>(); headers.put("x-amz-acl", Arrays.asList(new String[] { "public-read" })); assertEquals("OK", conn.createBucket(bucketName, null, headers).connection.getResponseMessage()); HttpClient httpClient = new HttpClient(); HeadMethod headMethod = new HeadMethod(objectUri); int rc = httpClient.executeMethod(headMethod); assertEquals(200, rc); System.out.println(FileUtils.readFileToString(new File(String.format("%s/%s/%s%s", BUCKET_ROOT, bucketName, objectName, ObjectMetaData.FILE_SUFFIX)))); assertEquals(Integer.toString(testData.length()), headMethod.getResponseHeaders(HttpHeaders.CONTENT_LENGTH)[0].getValue()); assertEquals(ObjectMetaData.DEFAULT_OBJECT_CONTENT_TYPE, headMethod.getResponseHeaders(HttpHeaders.CONTENT_TYPE)[0].getValue()); }
private void acquireLength() throws URISyntaxException, HttpException, IOException { HttpMethod head = new HeadMethod(url); int code = http.executeMethod(head); if(code != 200) { throw new IOException("Unable to retrieve from " + url); } Header lengthHeader = head.getResponseHeader(CONTENT_LENGTH); if(lengthHeader == null) { throw new IOException("No Content-Length header for " + url); } String val = lengthHeader.getValue(); try { length = Long.parseLong(val); } catch(NumberFormatException e) { throw new IOException("Bad Content-Length value " +url+ ": " + val); } }
/** * Determines the type of this file. Must not return null. The return * value of this method is cached, so the implementation can be expensive. */ protected FileType doGetType() throws Exception { // Use the HEAD method to probe the file. method = new HeadMethod(); setupMethod(method); final HttpClient client = fileSystem.getClient(); final int status = client.executeMethod(method); method.releaseConnection(); if (status == HttpURLConnection.HTTP_OK) { return FileType.FILE; } else if (status == HttpURLConnection.HTTP_NOT_FOUND || status == HttpURLConnection.HTTP_GONE) { return FileType.IMAGINARY; } else { throw new FileSystemException("vfs.provider.http/head.error", getName()); } }
/** * Returns <code>true</code> if the resource given as URL does exist. * @param client * @param httpURL * @return <code>true</code>if the resource exists * @throws IOException * @throws HttpException */ public static boolean resourceExists(HttpClient client, HttpURL httpURL) throws IOException, HttpException { HeadMethod head = new HeadMethod(httpURL.getURI()); head.setFollowRedirects(true); int status = client.executeMethod(head); switch (status) { case WebdavStatus.SC_OK: return true; case WebdavStatus.SC_NOT_FOUND: return false; default: HttpException ex = new HttpException(); ex.setReasonCode(status); ex.setReason(head.getStatusText()); throw ex; } }
/** * Checks the method being received and created a * suitable ResponseHandler for this method. * * @param method Method to handle * @return The handler for this response * @throws MethodNotAllowedException If no method could be choose this exception is thrown */ public static ResponseHandler createResponseHandler(HttpMethod method) throws MethodNotAllowedException { if (!AllowedMethodHandler.methodAllowed(method)) { throw new MethodNotAllowedException("The method " + method.getName() + " is not in the AllowedHeaderHandler's list of allowed methods.", AllowedMethodHandler.getAllowHeader()); } ResponseHandler handler = null; if (method.getName().equals("OPTIONS")) { handler = new OptionsResponseHandler((OptionsMethod) method); } else if (method.getName().equals("GET")) { handler = new GetResponseHandler((GetMethod) method); } else if (method.getName().equals("HEAD")) { handler = new HeadResponseHandler((HeadMethod) method); } else if (method.getName().equals("POST")) { handler = new PostResponseHandler((PostMethod) method); } else if (method.getName().equals("PUT")) { handler = new PutResponseHandler((PutMethod) method); } else if (method.getName().equals("DELETE")) { handler = new DeleteResponseHandler((DeleteMethod) method); } else if (method.getName().equals("TRACE")) { handler = new TraceResponseHandler((TraceMethod) method); } else { throw new MethodNotAllowedException("The method " + method.getName() + " was allowed by the AllowedMethodHandler, not by the factory.", handledMethods); } return handler; }
@Test public void htmlHead() throws IOException { final HeadMethod head = new HeadMethod(HTML_URL); final int status = H.getHttpClient().executeMethod(head); assertEquals(200, status); assertNull("Expecting null body", head.getResponseBody()); assertCommonHeaders(head, "text/html"); }
@Test public void pngHead() throws IOException { final HeadMethod head = new HeadMethod(PNG_URL); final int status = H.getHttpClient().executeMethod(head); assertEquals(200, status); assertNull("Expecting null body", head.getResponseBody()); assertCommonHeaders(head, "image/png"); }
public HttpResponse head(final RequestContext rq, Binding cmisBinding, String version, String cmisOperation) throws IOException { RestApiEndpoint endpoint = new RestApiEndpoint(rq.getNetworkId(), cmisBinding, version, cmisOperation, null); String url = endpoint.getUrl(); HeadMethod req = new HeadMethod(url.toString()); return submitRequest(req, rq); }
public void testHeadBasicAuthentication() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); HttpState state = new HttpState(); AuthScope authscope = new AuthScope( this.server.getLocalAddress(), this.server.getLocalPort(), "test"); state.setCredentials(authscope, creds); this.client.setState(state); this.server.setRequestHandler(handlerchain); HeadMethod head = new HeadMethod("/test/"); try { this.client.executeMethod(head); } finally { head.releaseConnection(); } assertNotNull(head.getStatusLine()); assertEquals(HttpStatus.SC_OK, head.getStatusLine().getStatusCode()); Header auth = head.getRequestHeader("Authorization"); assertNotNull(auth); String expected = "Basic " + EncodingUtil.getAsciiString( Base64.encodeBase64(EncodingUtil.getAsciiBytes("testuser:testpass"))); assertEquals(expected, auth.getValue()); AuthState authstate = head.getHostAuthState(); assertNotNull(authstate.getAuthScheme()); assertTrue(authstate.getAuthScheme() instanceof BasicScheme); assertEquals("test", authstate.getRealm()); }
/** * Send a HEAD request * @param cluster the cluster definition * @param path the path or URI * @param headers the HTTP headers to include in the request * @return a Response object with response detail * @throws IOException */ public Response head(Cluster cluster, String path, Header[] headers) throws IOException { HeadMethod method = new HeadMethod(); try { int code = execute(cluster, method, null, path); headers = method.getResponseHeaders(); return new Response(code, headers, null); } finally { method.releaseConnection(); } }
/** * Please see list of status codes and their meaning: * <br><br> * 204 No Content: URN is in database. No further information asked.<br> * 301 Moved Permanently: The given URN is replaced with a newer version. This newer version should be used instead.<br> * 404 Not Found: The given URN is not registered in system.<br> * 410 Gone: The given URN is registered in system but marked inactive.<br> * * @return the status code of the request */ public int head(MCRURN urn) { HeadMethod headMethod = new HeadMethod(getConfiguration().getServiceURL() + urn); try { return getHttpClient().executeMethod(headMethod); } catch (IOException e) { throw new RuntimeException(e); } finally { headMethod.releaseConnection(); } }
public static void checkUrlExistence(final String url) { if (url.toLowerCase().startsWith("http") || url.toLowerCase().startsWith("https")) { final HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager()); final HeadMethod httphead = new HeadMethod(url); try { if (httpClient.executeMethod(httphead) != HttpStatus.SC_OK) { throw new IllegalArgumentException("Invalid URL: " + url); } } catch (final HttpException hte) { throw new IllegalArgumentException("Cannot reach URL: " + url); } catch (final IOException ioe) { throw new IllegalArgumentException("Cannot reach URL: " + url); } } }
/** * Check if a file exists in the OC server * * @deprecated Use ExistenceCheckOperation instead * * @return 'true' if the file exists; 'false' it doesn't exist * @throws Exception When the existence could not be determined */ @Deprecated public boolean existsFile(String path) throws IOException, HttpException { HeadMethod head = new HeadMethod(getWebdavUri() + WebdavUtils.encodePath(path)); try { int status = executeMethod(head); Log_OC.d(TAG, "HEAD to " + path + " finished with HTTP status " + status + ((status != HttpStatus.SC_OK)?"(FAIL)":"")); exhaustResponse(head.getResponseBodyAsStream()); return (status == HttpStatus.SC_OK); } finally { head.releaseConnection(); // let the connection available for other methods } }
/** * Create a Commons HttpMethodBase object for the given HTTP method and URI specification. * @param httpMethod the HTTP method * @param uri the URI * @return the Commons HttpMethodBase object */ protected HttpMethodBase createCommonsHttpMethod(HttpMethod httpMethod, String uri) { switch (httpMethod) { case GET: return new GetMethod(uri); case DELETE: return new DeleteMethod(uri); case HEAD: return new HeadMethod(uri); case OPTIONS: return new OptionsMethod(uri); case POST: return new PostMethod(uri); case PUT: return new PutMethod(uri); case TRACE: return new TraceMethod(uri); default: throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod); } }
public long getSize(String url) { HeadMethod method = new HeadMethod(url); try { int iRet = _client.executeMethod(method); if (iRet != 200) { return 0; } long iLen = getLength(method); return (iLen == 177 ? 0 : iLen); } catch (Exception e) { e.printStackTrace(); return 0; } }
public void head(IdProof assertion, String path) throws ServiceException { try { HeadMethod method = new HeadMethod(baseUrl + "/" + path); method.setRequestHeader(AuthenticationHeader.HEADER_NAME, AuthenticationHeader.encode(assertion)); int result = httpClient.executeMethod(method); if (result != 200) { throw new ServiceException(result); } } catch (IOException ex) { throw new ServiceFailure(ex); } }
@Override public FileObject getFile(String uri) throws FileNotFoundException { HttpMethod method = new HeadMethod(uri); try { int sc = client.executeMethod(method); FileObject file = null; if (sc == HttpServletResponse.SC_NOT_FOUND) { file = new HttpFileObject(uri, new HttpHeaders(method.getResponseHeaders()), false); } else if (sc != HttpServletResponse.SC_OK && sc != HttpServletResponse.SC_PARTIAL_CONTENT) { throw new FileNotFoundException(uri + "response statue: " + sc); } else { HttpHeaders header = new HttpHeaders(method.getResponseHeaders()); if (!header.acceptRanges()) { throw new IOException("server can't accept ranges"); } file = new HttpFileObject(uri, new HttpHeaders(method.getResponseHeaders()), true); } return file; } catch (IOException e) { throw new FileNotFoundException("error for call [" + uri + "]"); } finally { method.releaseConnection(); } }
protected String getHeader(String header) throws URISyntaxException, HttpException, IOException { HttpMethod head = new HeadMethod(url); int code = http.executeMethod(head); if(code != 200) { throw new IOException("Unable to retrieve from " + url); } Header theHeader = head.getResponseHeader(header); if(theHeader == null) { throw new IOException("No " + header + " header for " + url); } String val = theHeader.getValue(); return val; }
private static String getRemoteFilename(String url) throws IOException, HTTPException { HttpClient client = new HttpClient(); HeadMethod get = new HeadMethod(url); get.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); int code = client.executeMethod(get); if (code >= 200 && code < 400) { Header disposition = get.getResponseHeader("Content-Disposition"); if (disposition != null) return disposition.getValue().replace("attachment; filename=", ""); } Logger.getLogger(IOUtils.class).fatal("Got HTTP response code " + code + " when trying to download " + url + ". Returning null."); return null; }