List of usage examples for org.apache.http.client.methods HttpHead HttpHead
public HttpHead(final String uri)
From source file:com.streamreduce.AbstractInContainerTestCase.java
/** * Makes a request to the given url using the given method and possibly submitting * the given data. If you need the request to be an authenticated request, pass in * your authentication token as well.// w w w. j a va2 s. com * * @param url the url for the request * @param method the method to use for the request * @param data the data, if any, for the request * @param authnToken the token retrieved during authentication * @param type API or GATEWAY, tells us the auth token key to use * @return the response as string (This is either the response payload or the status code if no payload is sent) * @throws Exception if something goes wrong */ public String makeRequest(String url, String method, Object data, String authnToken, AuthTokenType type) throws Exception { HttpClient httpClient = new DefaultHttpClient(); HttpRequestBase request; String actualPayload; // Set the User-Agent to be safe httpClient.getParams().setParameter(HttpProtocolParams.USER_AGENT, Constants.NODEABLE_HTTP_USER_AGENT); // Create the request object if (method.equals("DELETE")) { request = new HttpDelete(url); } else if (method.equals("GET")) { request = new HttpGet(url); } else if (method.equals("POST")) { request = new HttpPost(url); } else if (method.equals("PUT")) { request = new HttpPut(url); } else if (method.equals("HEAD")) { request = new HttpHead(url); } else { throw new IllegalArgumentException("The method you specified is not supported."); } // Put data into the request for POST and PUT requests if (method.equals("POST") || method.equals("PUT")) { HttpEntityEnclosingRequestBase eeMethod = (HttpEntityEnclosingRequestBase) request; String requestBody = data instanceof JSONObject ? ((JSONObject) data).toString() : new ObjectMapper().writeValueAsString(data); eeMethod.setEntity(new StringEntity(requestBody, MediaType.APPLICATION_JSON, "UTF-8")); } // Add the authentication token to the request if (authnToken != null) { if (type.equals(AuthTokenType.API)) { request.addHeader(Constants.NODEABLE_AUTH_TOKEN, authnToken); } else if (type.equals(AuthTokenType.GATEWAY)) { request.addHeader(Constants.NODEABLE_API_KEY, authnToken); } else { throw new Exception("Unsupported Type of " + type + " for authToken " + authnToken); } } // Execute the request try { HttpResponse response = httpClient.execute(request); String payload = IOUtils.toString(response.getEntity().getContent()); // To work around HEAD, where we cannot receive a payload, and other scenarios where the payload could // be empty, let's stuff the response status code into the response. actualPayload = payload != null && payload.length() > 0 ? payload : Integer.toString(response.getStatusLine().getStatusCode()); } finally { request.releaseConnection(); } return actualPayload; }
From source file:org.apache.marmotta.platform.core.services.content.HTTPContentReader.java
/** * Return the number of bytes the content of this resource contains. * * @param resource resource for which to return the content length * @return byte count for the resource content *//*from ww w. jav a 2s . c om*/ @Override public long getContentLength(Resource resource, String mimetype) { try { RepositoryConnection conn = sesameService.getConnection(); try { MediaContentItem mci = FacadingFactory.createFacading(conn).createFacade(resource, MediaContentItem.class); String location = mci.getContentLocation(); // if no location is explicitly specified, use the resource URI itself if (location == null && resource instanceof URI && resource.stringValue().startsWith("http://")) { location = resource.stringValue(); } try { if (location != null) { log.info("reading remote resource {}", location); HttpHead head = new HttpHead(location); return httpClientService.execute(head, new ResponseHandler<Long>() { @Override public Long handleResponse(HttpResponse response) throws ClientProtocolException, IOException { if (response.getStatusLine().getStatusCode() == 200) return Long.parseLong(response.getFirstHeader("Content-Length").getValue()); else return 0l; } }); } else return 0; } catch (Exception ex) { return 0; } } finally { conn.commit(); conn.close(); } } catch (RepositoryException ex) { handleRepositoryException(ex, FileSystemContentReader.class); return 0; } }
From source file:com.olleh.ucloudbiz.ucloudstorage.FilesClientExt.java
/** * <p>/*from w ww . j av a 2 s . co m*/ * FilesContainerInfo static website container logging . * </p> * * @param containerName * container * @return FilesContainerInfoExt * * @see <A HREF="../../../../com/rackspacecloud/client/cloudfiles/FilesClient.html#getContainerInfo(java.lang.String)"><CODE>FilesClient.getContainerInfo(String)</CODE></A>, * <A HREF="../../../../com/rackspacecloud/client/cloudfiles/FilesContainerInfo.html"><CODE>FilesContainerInfo</CODE></A>, * <A HREF="../../../../com/kt/client/ucloudstorage/FilesContainerInfoExt.html"><CODE>FilesContainerInfoExt</CODE></A> */ public FilesContainerInfoExt getContainerInfoExt(String containerName) throws IOException, HttpException, FilesException { if (this.isLoggedin()) { if (isValidContainerName(containerName)) { HttpHead method = null; try { method = new HttpHead(storageURL + "/" + sanitizeForURI(containerName)); method.getParams().setIntParameter("http.socket.timeout", connectionTimeOut); method.setHeader(FilesConstants.X_AUTH_TOKEN, authToken); FilesResponseExt response = new FilesResponseExt(client.execute(method)); if (response.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { method.removeHeaders(FilesConstants.X_AUTH_TOKEN); if (login()) { method = new HttpHead(storageURL + "/" + sanitizeForURI(containerName)); method.getParams().setIntParameter("http.socket.timeout", connectionTimeOut); method.setHeader(FilesConstants.X_AUTH_TOKEN, authToken); response = new FilesResponseExt(client.execute(method)); } else { throw new FilesAuthorizationException("Re-login failed", response.getResponseHeaders(), response.getStatusLine()); } } if (response.getStatusCode() == HttpStatus.SC_NO_CONTENT) { int objCount = response.getContainerObjectCount(); long objSize = response.getContainerBytesUsed(); String webIndex = response.getWebIndex(); String webError = response.getWebError(); boolean statusListing = response.getWebListings(); String webCss = response.getWebCss(); boolean statusLogging = response.getContainerLogging(); return new FilesContainerInfoExt(containerName, objCount, objSize, webIndex, webError, statusListing, webCss, statusLogging); } else if (response.getStatusCode() == HttpStatus.SC_NOT_FOUND) { throw new FilesNotFoundException("Container not found: " + containerName, response.getResponseHeaders(), response.getStatusLine()); } else { throw new FilesException("Unexpected result from server", response.getResponseHeaders(), response.getStatusLine()); } } finally { if (method != null) method.abort(); } } else { throw new FilesInvalidNameException(containerName); } } else throw new FilesAuthorizationException("You must be logged in", null, null); }
From source file:org.hyperic.hq.plugin.netservices.HTTPCollector.java
public void collect() { if (isPingCompat.get()) { // back compat w/ old url.availability templates super.collect(); return;/*from www.ja va2 s . co m*/ } this.matches.clear(); HttpConfig config = new HttpConfig(getTimeoutMillis(), getTimeoutMillis(), proxyHost.get(), proxyPort.get()); AgentKeystoreConfig keystoreConfig = new AgentKeystoreConfig(); log.debug("isAcceptUnverifiedCert:" + keystoreConfig.isAcceptUnverifiedCert()); HQHttpClient client = new HQHttpClient(keystoreConfig, config, keystoreConfig.isAcceptUnverifiedCert()); HttpParams params = client.getParams(); params.setParameter(CoreProtocolPNames.USER_AGENT, useragent.get()); if (this.hosthdr != null) { params.setParameter(ClientPNames.VIRTUAL_HOST, this.hosthdr); } HttpRequestBase request; double avail = 0; try { if (getMethod().equals(HttpHead.METHOD_NAME)) { request = new HttpHead(getURL()); addParams(request, this.params.get()); } else if (getMethod().equals(HttpPost.METHOD_NAME)) { HttpPost httpPost = new HttpPost(getURL()); request = httpPost; addParams(httpPost, this.params.get()); } else { request = new HttpGet(getURL()); addParams(request, this.params.get()); } request.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, isFollow()); addCredentials(request, client); startTime(); HttpResponse response = client.execute(request); int statusCode = response.getStatusLine().getStatusCode(); int tries = 0; while (statusCode == HttpURLConnection.HTTP_MOVED_TEMP && tries < 3) { tries++; Header header = response.getFirstHeader("Location"); String url = header.getValue(); String[] toks = url.split(";"); String[] t = toks.length > 1 ? toks[1].split("\\?") : new String[0]; response = getRedirect(toks[0], t.length > 1 ? t[1] : ""); statusCode = response.getStatusLine().getStatusCode(); } endTime(); setResponseCode(statusCode); avail = getAvail(statusCode); StringBuilder msg = new StringBuilder(String.valueOf(statusCode)); Header header = response.getFirstHeader("Server"); msg.append(header != null ? " (" + header.getValue() + ")" : ""); setLastModified(response, statusCode); avail = checkPattern(response, avail, msg); setAvailMsg(avail, msg); } catch (UnsupportedEncodingException e) { log.error("unsupported encoding: " + e, e); } catch (IOException e) { avail = Metric.AVAIL_DOWN; setErrorMessage(e.toString()); } finally { setAvailability(avail); } netstat(); }
From source file:de.taimos.httputils.HTTPRequest.java
/** * @param executor Thread pool/*from w w w . jav a 2s .c om*/ * @param callback {@link HTTPResponseCallback} */ public void headAsync(final Executor executor, final HTTPResponseCallback callback) { this.executeAsync(executor, new HttpHead(this.buildURI()), callback); }
From source file:com.nesscomputing.httpclient.factory.httpclient4.ApacheHttpClient4Factory.java
@Override public <T> T performRequest(final HttpClientRequest<T> incomingRequest) throws IOException { checkRunning();/*from w w w . ja v a 2 s . c om*/ HttpClientRequest<T> request = incomingRequest; if (CollectionUtils.isNotEmpty(httpClientObservers)) { LOG.trace("Executing Observers"); for (HttpClientObserver observer : httpClientObservers) { request = observer.<T>onRequestSubmitted(request); } if (request != incomingRequest) { LOG.trace("Request was modified by Observers!"); } } request = contributeAcceptEncoding(request); LOG.trace("Got a '%s' request", request.getHttpMethod()); switch (request.getHttpMethod()) { case DELETE: return executeRequest(new HttpDelete(request.getUri()), request); case HEAD: return executeRequest(new HttpHead(request.getUri()), request); case OPTIONS: return executeRequest(new HttpOptions(request.getUri()), request); case POST: final HttpPost httpPost = new HttpPost(request.getUri()); final HttpClientBodySource postSource = request.getHttpBodySource(); if (postSource instanceof InternalHttpBodySource) { httpPost.setEntity(((InternalHttpBodySource) postSource).getHttpEntity()); } return executeRequest(httpPost, request); case PUT: final HttpPut httpPut = new HttpPut(request.getUri()); final HttpClientBodySource putSource = request.getHttpBodySource(); if (putSource instanceof InternalHttpBodySource) { httpPut.setEntity(((InternalHttpBodySource) putSource).getHttpEntity()); } return executeRequest(httpPut, request); case GET: return executeRequest(new HttpGet(request.getUri()), request); default: LOG.warn("Got an unknown request type: '%s', falling back to GET", request.getHttpMethod()); return executeRequest(new HttpGet(request.getUri()), request); } }
From source file:org.artifactory.webapp.wicket.page.config.repos.remote.HttpRepoPanel.java
protected HttpRequestBase getRemoteRepoTestMethod(String url) { HttpRequestBase testMethod = null;/* www . j av a 2s . c o m*/ HttpRepoDescriptor repo = getRepoDescriptor(); if (repo.getType().equals(RepoType.Gems)) { GemsWebAddon gemsAddon = addons.addonByType(GemsWebAddon.class); testMethod = gemsAddon.getRemoteRepoTestMethod(url, repo); } if (testMethod == null) { testMethod = addons.addonByType(NuGetWebAddon.class).getRemoteRepoTestMethod(url, repo); } if (testMethod == null) { testMethod = new HttpHead(HttpUtils.encodeQuery(url)); } return testMethod; }
From source file:at.orz.arangodb.http.HttpManager.java
/** * //from www . j a va 2s . co m * @param requestEntity * @return * @throws ArangoException */ public HttpResponseEntity execute(HttpRequestEntity requestEntity) throws ArangoException { String url = buildUrl(requestEntity); if (logger.isDebugEnabled()) { if (requestEntity.type == RequestType.POST || requestEntity.type == RequestType.PUT || requestEntity.type == RequestType.PATCH) { logger.debug("[REQ]http-{}: url={}, headers={}, body={}", new Object[] { requestEntity.type, url, requestEntity.headers, requestEntity.bodyText }); } else { logger.debug("[REQ]http-{}: url={}, headers={}", new Object[] { requestEntity.type, url, requestEntity.headers }); } } HttpRequestBase request = null; switch (requestEntity.type) { case GET: request = new HttpGet(url); break; case POST: HttpPost post = new HttpPost(url); configureBodyParams(requestEntity, post); request = post; break; case PUT: HttpPut put = new HttpPut(url); configureBodyParams(requestEntity, put); request = put; break; case PATCH: HttpPatch patch = new HttpPatch(url); configureBodyParams(requestEntity, patch); request = patch; break; case HEAD: request = new HttpHead(url); break; case DELETE: request = new HttpDelete(url); break; } // common-header String userAgent = "Mozilla/5.0 (compatible; ArangoDB-JavaDriver/1.0; +http://mt.orz.at/)"; // TODO: request.setHeader("User-Agent", userAgent); //request.setHeader("Content-Type", "binary/octet-stream"); // optinal-headers if (requestEntity.headers != null) { for (Entry<String, Object> keyValue : requestEntity.headers.entrySet()) { request.setHeader(keyValue.getKey(), keyValue.getValue().toString()); } } // Basic Auth Credentials credentials = null; if (requestEntity.username != null && requestEntity.password != null) { credentials = new UsernamePasswordCredentials(requestEntity.username, requestEntity.password); } else if (configure.getUser() != null && configure.getPassword() != null) { credentials = new UsernamePasswordCredentials(configure.getUser(), configure.getPassword()); } if (credentials != null) { request.addHeader(BasicScheme.authenticate(credentials, "US-ASCII", false)); } // CURL/httpie Logger if (configure.isEnableCURLLogger()) { CURLLogger.log(url, requestEntity, userAgent, credentials); } HttpResponse response = null; try { response = client.execute(request); if (response == null) { return null; } HttpResponseEntity responseEntity = new HttpResponseEntity(); // http status StatusLine status = response.getStatusLine(); responseEntity.statusCode = status.getStatusCode(); responseEntity.statusPhrase = status.getReasonPhrase(); logger.debug("[RES]http-{}: statusCode={}", requestEntity.type, responseEntity.statusCode); // ?? //// TODO etag??? Header etagHeader = response.getLastHeader("etag"); if (etagHeader != null) { responseEntity.etag = Long.parseLong(etagHeader.getValue().replace("\"", "")); } // Map??? responseEntity.headers = new TreeMap<String, String>(); for (Header header : response.getAllHeaders()) { responseEntity.headers.put(header.getName(), header.getValue()); } // ??? HttpEntity entity = response.getEntity(); if (entity != null) { Header contentType = entity.getContentType(); if (contentType != null) { responseEntity.contentType = contentType.getValue(); if (responseEntity.isDumpResponse()) { responseEntity.stream = entity.getContent(); logger.debug("[RES]http-{}: stream, {}", requestEntity.type, contentType.getValue()); } } // Close stream in this method. if (responseEntity.stream == null) { responseEntity.text = IOUtils.toString(entity.getContent()); logger.debug("[RES]http-{}: text={}", requestEntity.type, responseEntity.text); } } return responseEntity; } catch (ClientProtocolException e) { throw new ArangoException(e); } catch (IOException e) { throw new ArangoException(e); } }
From source file:org.sonatype.nexus.proxy.storage.remote.httpclient.HttpClientRemoteStorage.java
@Override protected boolean checkRemoteAvailability(final long newerThen, final ProxyRepository repository, final ResourceStoreRequest request, final boolean isStrict) throws RemoteStorageException { final URL remoteUrl = appendQueryString(getAbsoluteUrlFromBase(repository, request), repository); HttpRequestBase method;/*w w w . jav a 2s . c om*/ HttpResponse httpResponse = null; int statusCode = HttpStatus.SC_BAD_REQUEST; // artifactory hack, it pukes on HEAD so we will try with GET if HEAD fails boolean doGet = false; { method = new HttpHead(remoteUrl.toExternalForm()); try { httpResponse = executeRequestAndRelease(repository, request, method); statusCode = httpResponse.getStatusLine().getStatusCode(); } catch (RemoteStorageException e) { // If HEAD failed, attempt a GET. Some repos may not support HEAD method doGet = true; getLogger().debug("HEAD method failed, will attempt GET. Exception: " + e.getMessage(), e); } finally { // HEAD returned error, but not exception, try GET before failing if (!doGet && statusCode != HttpStatus.SC_OK) { doGet = true; getLogger().debug("HEAD method failed, will attempt GET. Status: " + statusCode); } } } { if (doGet) { // create a GET method = new HttpGet(remoteUrl.toExternalForm()); // execute it httpResponse = executeRequestAndRelease(repository, request, method); statusCode = httpResponse.getStatusLine().getStatusCode(); } } // if we are not strict and remote is S3 if (!isStrict && isRemotePeerAmazonS3Storage(repository)) { // if we are relaxed, we will accept any HTTP response code below 500. This means anyway the HTTP // transaction succeeded. This method was never really detecting that the remoteUrl really denotes a root of // repository (how could we do that?) // this "relaxed" check will help us to "pass" S3 remote storage. return statusCode >= HttpStatus.SC_OK && statusCode <= HttpStatus.SC_INTERNAL_SERVER_ERROR; } else { // non relaxed check is strict, and will select only the OK response if (statusCode == HttpStatus.SC_OK) { // we have it // we have newer if this below is true return makeDateFromHeader(httpResponse.getFirstHeader("last-modified")) > newerThen; } else if ((statusCode >= HttpStatus.SC_MULTIPLE_CHOICES && statusCode < HttpStatus.SC_BAD_REQUEST) || statusCode == HttpStatus.SC_NOT_FOUND) { return false; } else { throw new RemoteStorageException("Unexpected response code while executing " + method.getMethod() + " method [repositoryId=\"" + repository.getId() + "\", requestPath=\"" + request.getRequestPath() + "\", remoteUrl=\"" + remoteUrl.toString() + "\"]. Expected: \"SUCCESS (200)\". Received: " + statusCode + " : " + httpResponse.getStatusLine().getReasonPhrase()); } } }
From source file:com.cloudant.client.org.lightcouch.CouchDbClientBase.java
/** * Performs a HTTP HEAD request. * * @return {@link HttpResponse} */ HttpResponse head(URI uri) { return executeRequest(new HttpHead(uri)); }