List of usage examples for org.apache.commons.httpclient.methods HeadMethod HeadMethod
public HeadMethod(String paramString)
From source file:com.sun.jersey.client.apache.ApacheHttpClientHandler.java
private HttpMethod getHttpMethod(ClientRequest cr) { final String strMethod = cr.getMethod(); final String uri = cr.getURI().toString(); if (strMethod.equals("GET")) { return new GetMethod(uri); } else if (strMethod.equals("POST")) { return new PostMethod(uri); } else if (strMethod.equals("PUT")) { return new PutMethod(uri); } else if (strMethod.equals("DELETE")) { return new CustomMethod("DELETE", uri); } else if (strMethod.equals("HEAD")) { return new HeadMethod(uri); } else if (strMethod.equals("OPTIONS")) { return new OptionsMethod(uri); } else {/*w ww.j a v a 2s.c o m*/ return new CustomMethod(strMethod, uri); } }
From source file:com.gisgraphy.importer.ImporterHelper.java
/** * @param URL the HTTP URL// ww w . j ava2 s.c o m * @return The size of the HTTP file using HTTP head method * or -1 if error or the file doesn't exists */ public static long getHttpFileSize(String URL) { HeadMethod headMethod = new HeadMethod(URL); //we can not follow redirect because Geonames send a 302 found HTTP status code when a file doen't exists headMethod.setFollowRedirects(false); try { int code = client.executeMethod(headMethod); int firstDigitOfCode = code / 100; switch (firstDigitOfCode) { case 4: logger.error("Can not determine HTTP file size of " + URL + " because it does not exists (" + code + ")"); return -1; //needed to catch 3XX code because Geonames send a 302 found HTTP status code when a file doen't exists case 3: logger.error("Can not determine HTTP file size of " + URL + " because it does not exists (" + code + ")"); return -1; case 5: logger.error( "Can not determine HTTP file size of " + URL + " because the server send an error " + code); return -1; default: break; } Header[] contentLengthHeaders = headMethod.getResponseHeaders("Content-Length"); if (contentLengthHeaders.length == 1) { logger.info("HTTP file size of " + URL + " = " + contentLengthHeaders[0].getValue()); return new Long(contentLengthHeaders[0].getValue()); } else if (contentLengthHeaders.length <= 0) { return -1L; } } catch (HttpException e) { logger.error("can not execute head method for " + URL + " : " + e.getMessage(), e); } catch (IOException e) { logger.error("can not execute head method for " + URL + " : " + e.getMessage(), e); } finally { headMethod.releaseConnection(); } return -1; }
From source file:com.atlantbh.jmeter.plugins.oauth.OAuthSampler.java
private HttpMethodBase createHttpMethod(String method, String urlStr) { HttpMethodBase httpMethod;/*from w w w. j av a 2 s . c om*/ // May generate IllegalArgumentException if (method.equals(POST)) { httpMethod = new PostMethod(urlStr); } else if (method.equals(PUT)) { httpMethod = new PutMethod(urlStr); } else if (method.equals(HEAD)) { httpMethod = new HeadMethod(urlStr); } else if (method.equals(TRACE)) { httpMethod = new TraceMethod(urlStr); } else if (method.equals(OPTIONS)) { httpMethod = new OptionsMethod(urlStr); } else if (method.equals(DELETE)) { httpMethod = new DeleteMethod(urlStr); } else if (method.equals(GET)) { httpMethod = new GetMethod(urlStr); } else { log.error("Unexpected method (converted to GET): " + method); httpMethod = new GetMethod(urlStr); } return httpMethod; }
From source file:com.sittinglittleduck.DirBuster.Worker.java
private HttpMethodBase createHttpMethod(String method, String url) { switch (method.toUpperCase()) { case "HEAD": return new HeadMethod(url); case "GET": return new GetMethod(url); default://from w w w. j a v a 2 s. co m throw new IllegalStateException("Method not yet created"); } }
From source file:com.cloud.utils.UriUtils.java
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 {/* w w w. j av a 2 s. c om*/ if (httpClient.executeMethod(httphead) != HttpStatus.SC_OK) { throw new IllegalArgumentException("Invalid URL: " + url); } } catch (HttpException hte) { throw new IllegalArgumentException("Cannot reach URL: " + url); } catch (IOException ioe) { throw new IllegalArgumentException("Cannot reach URL: " + url); } } }
From source file:com.cloudbees.api.BeesClient.java
/** * Sends a request in JSON and expects a JSON response back. * * @param urlTail The end point to hit. Appended to {@link #base}. Shouldn't start with '/' * @param method HTTP method name like GET or POST. * @param headers//from w w w.j a va 2 s .c o m *@param jsonContent The json request payload, or null if none. @throws IOException If the communication fails. */ public HttpReply jsonRequest(String urlTail, String method, Map<String, String> headers, String jsonContent) throws IOException { HttpMethodBase httpMethod; String urlString = absolutize(urlTail); trace("API call: " + urlString); if (method.equalsIgnoreCase("GET")) { httpMethod = new GetMethod(urlString); } else if ((method.equalsIgnoreCase("POST"))) { httpMethod = new PostMethod(urlString); } else if ((method.equalsIgnoreCase("PUT"))) { httpMethod = new PutMethod(urlString); } else if ((method.equalsIgnoreCase("DELETE"))) { httpMethod = new DeleteMethod(urlString); } else if ((method.equalsIgnoreCase("PATCH"))) { httpMethod = new PatchMethod(urlString); } else if ((method.equalsIgnoreCase("HEAD"))) { httpMethod = new HeadMethod(urlString); } else if ((method.equalsIgnoreCase("TRACE"))) { httpMethod = new TraceMethod(urlString); } else if ((method.equalsIgnoreCase("OPTIONS"))) { httpMethod = new OptionsMethod(urlString); } else throw new IOException("Method not supported: " + method); httpMethod.setRequestHeader("Accept", "application/json"); if (jsonContent != null && httpMethod instanceof EntityEnclosingMethod) { StringRequestEntity requestEntity = new StringRequestEntity(jsonContent, "application/json", "UTF-8"); ((EntityEnclosingMethod) httpMethod).setRequestEntity(requestEntity); trace("Payload: " + jsonContent); } return executeRequest(httpMethod, headers); }
From source file:com.gnizr.core.util.GnizrDaoUtil.java
public static Integer detectMIMEType(String url) { try {//ww w .ja v a 2 s. co m HttpClient httpClient = new HttpClient(); HeadMethod method = new HeadMethod(url); method.getParams().setIntParameter("http.socket.timeout", 5000); int code = httpClient.executeMethod(method); if (code == 200) { Header h = method.getResponseHeader("Content-Type"); if (h != null) { HeaderElement[] headElm = h.getElements(); if (headElm != null & headElm.length > 0) { String mimeType = headElm[0].getValue(); if (mimeType == null) { mimeType = headElm[0].getName(); } if (mimeType != null) { return getMimeTypeIdCode(mimeType); } } } } } catch (Exception e) { // no code; } return MIMEType.UNKNOWN; }
From source file:com.xmlcalabash.library.ApacheHttpRequest.java
private HeadMethod doHead() { HeadMethod method = new HeadMethod(requestURI.toASCIIString()); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); for (Header header : headers) { method.addRequestHeader(header); }/*from ww w. j av a 2s .c om*/ return method; }
From source file:edu.indiana.d2i.registryext.RegistryExtAgent.java
/** * check whether a resource exists// w ww . j a v a2s .c om * * @param repoPath * path in registry * @return * @throws HttpException * @throws IOException * @throws RegistryExtException * @throws OAuthSystemException * @throws OAuthProblemException */ public boolean isResourceExist(String repoPath) throws HttpException, IOException, RegistryExtException, OAuthSystemException, OAuthProblemException { Map<String, Object> session = ActionContext.getContext().getSession(); int statusCode = 200; String accessToken = (String) session.get(Constants.SESSION_TOKEN); boolean exist = true; String requestURL = composeURL(FILEOPPREFIX, repoPath); if (logger.isDebugEnabled()) { logger.debug("Check existence request URL=" + requestURL); } HttpClient httpclient = new HttpClient(); HeadMethod head = new HeadMethod(requestURL); head.addRequestHeader("Authorization", "Bearer " + accessToken); try { httpclient.executeMethod(head); statusCode = head.getStatusLine().getStatusCode(); /* handle token expiration */ if (statusCode == 401) { logger.info(String.format("Access token %s expired, going to refresh it", accessToken)); refreshToken(session); // use refreshed access token accessToken = (String) session.get(Constants.SESSION_TOKEN); head.addRequestHeader("Authorization", "Bearer " + accessToken); // re-send the request httpclient.executeMethod(head); statusCode = head.getStatusLine().getStatusCode(); } if (statusCode == 404) exist = false; else if (statusCode != 200) { throw new RegistryExtException( "Failed in checking resource existence: HTTP error code : " + statusCode); } } finally { if (head != null) head.releaseConnection(); } return exist; }
From source file:com.ning.http.client.providers.apache.ApacheAsyncHttpProvider.java
private HttpMethodBase createMethod(HttpClient client, Request request) throws IOException, FileNotFoundException { String methodName = request.getMethod(); HttpMethodBase method = null;/* w ww . j a v a 2s. c o m*/ if (methodName.equalsIgnoreCase("POST") || methodName.equalsIgnoreCase("PUT")) { EntityEnclosingMethod post = methodName.equalsIgnoreCase("POST") ? new PostMethod(request.getUrl()) : new PutMethod(request.getUrl()); String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding(); post.getParams().setContentCharset("ISO-8859-1"); if (request.getByteData() != null) { post.setRequestEntity(new ByteArrayRequestEntity(request.getByteData())); post.setRequestHeader("Content-Length", String.valueOf(request.getByteData().length)); } else if (request.getStringData() != null) { post.setRequestEntity(new StringRequestEntity(request.getStringData(), "text/xml", bodyCharset)); post.setRequestHeader("Content-Length", String.valueOf(request.getStringData().getBytes(bodyCharset).length)); } else if (request.getStreamData() != null) { InputStreamRequestEntity r = new InputStreamRequestEntity(request.getStreamData()); post.setRequestEntity(r); post.setRequestHeader("Content-Length", String.valueOf(r.getContentLength())); } else if (request.getParams() != null) { StringBuilder sb = new StringBuilder(); for (final Map.Entry<String, List<String>> paramEntry : request.getParams()) { final String key = paramEntry.getKey(); for (final String value : paramEntry.getValue()) { if (sb.length() > 0) { sb.append("&"); } UTF8UrlEncoder.appendEncoded(sb, key); sb.append("="); UTF8UrlEncoder.appendEncoded(sb, value); } } post.setRequestHeader("Content-Length", String.valueOf(sb.length())); post.setRequestEntity(new StringRequestEntity(sb.toString(), "text/xml", "ISO-8859-1")); if (!request.getHeaders().containsKey("Content-Type")) { post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); } } else if (request.getParts() != null) { MultipartRequestEntity mre = createMultipartRequestEntity(bodyCharset, request.getParts(), post.getParams()); post.setRequestEntity(mre); post.setRequestHeader("Content-Type", mre.getContentType()); post.setRequestHeader("Content-Length", String.valueOf(mre.getContentLength())); } else if (request.getEntityWriter() != null) { post.setRequestEntity(new EntityWriterRequestEntity(request.getEntityWriter(), computeAndSetContentLength(request, post))); } else if (request.getFile() != null) { File file = request.getFile(); if (!file.isFile()) { throw new IOException( String.format(Thread.currentThread() + "File %s is not a file or doesn't exist", file.getAbsolutePath())); } post.setRequestHeader("Content-Length", String.valueOf(file.length())); FileInputStream fis = new FileInputStream(file); try { InputStreamRequestEntity r = new InputStreamRequestEntity(fis); post.setRequestEntity(r); post.setRequestHeader("Content-Length", String.valueOf(r.getContentLength())); } finally { fis.close(); } } else if (request.getBodyGenerator() != null) { Body body = request.getBodyGenerator().createBody(); try { int length = (int) body.getContentLength(); if (length < 0) { length = (int) request.getContentLength(); } // TODO: This is suboptimal if (length >= 0) { post.setRequestHeader("Content-Length", String.valueOf(length)); // This is totally sub optimal byte[] bytes = new byte[length]; ByteBuffer buffer = ByteBuffer.wrap(bytes); for (;;) { buffer.clear(); if (body.read(buffer) < 0) { break; } } post.setRequestEntity(new ByteArrayRequestEntity(bytes)); } } finally { try { body.close(); } catch (IOException e) { logger.warn("Failed to close request body: {}", e.getMessage(), e); } } } if (request.getHeaders().getFirstValue("Expect") != null && request.getHeaders().getFirstValue("Expect").equalsIgnoreCase("100-Continue")) { post.setUseExpectHeader(true); } method = post; } else if (methodName.equalsIgnoreCase("DELETE")) { method = new DeleteMethod(request.getUrl()); } else if (methodName.equalsIgnoreCase("HEAD")) { method = new HeadMethod(request.getUrl()); } else if (methodName.equalsIgnoreCase("GET")) { method = new GetMethod(request.getUrl()); } else if (methodName.equalsIgnoreCase("OPTIONS")) { method = new OptionsMethod(request.getUrl()); } else { throw new IllegalStateException(String.format("Invalid Method", methodName)); } ProxyServer proxyServer = request.getProxyServer() != null ? request.getProxyServer() : config.getProxyServer(); boolean avoidProxy = ProxyUtils.avoidProxy(proxyServer, request); if (!avoidProxy) { if (proxyServer.getPrincipal() != null) { Credentials defaultcreds = new UsernamePasswordCredentials(proxyServer.getPrincipal(), proxyServer.getPassword()); client.getState().setCredentials(new AuthScope(null, -1, AuthScope.ANY_REALM), defaultcreds); } ProxyHost proxyHost = proxyServer == null ? null : new ProxyHost(proxyServer.getHost(), proxyServer.getPort()); client.getHostConfiguration().setProxyHost(proxyHost); } method.setFollowRedirects(false); if ((request.getCookies() != null) && !request.getCookies().isEmpty()) { for (Cookie cookie : request.getCookies()) { method.setRequestHeader("Cookie", AsyncHttpProviderUtils.encodeCookies(request.getCookies())); } } if (request.getHeaders() != null) { for (String name : request.getHeaders().keySet()) { if (!"host".equalsIgnoreCase(name)) { for (String value : request.getHeaders().get(name)) { method.setRequestHeader(name, value); } } } } if (request.getHeaders().getFirstValue("User-Agent") != null) { method.setRequestHeader("User-Agent", request.getHeaders().getFirstValue("User-Agent")); } else if (config.getUserAgent() != null) { method.setRequestHeader("User-Agent", config.getUserAgent()); } else { method.setRequestHeader("User-Agent", AsyncHttpProviderUtils.constructUserAgent(ApacheAsyncHttpProvider.class)); } if (config.isCompressionEnabled()) { Header acceptableEncodingHeader = method.getRequestHeader("Accept-Encoding"); if (acceptableEncodingHeader != null) { String acceptableEncodings = acceptableEncodingHeader.getValue(); if (acceptableEncodings.indexOf("gzip") == -1) { StringBuilder buf = new StringBuilder(acceptableEncodings); if (buf.length() > 1) { buf.append(","); } buf.append("gzip"); method.setRequestHeader("Accept-Encoding", buf.toString()); } } else { method.setRequestHeader("Accept-Encoding", "gzip"); } } if (request.getVirtualHost() != null) { String vs = request.getVirtualHost(); int index = vs.indexOf(":"); if (index > 0) { vs = vs.substring(0, index); } method.getParams().setVirtualHost(vs); } return method; }