List of usage examples for org.apache.http.client.methods HttpHead HttpHead
public HttpHead(final String uri)
From source file:org.fcrepo.integration.http.api.FedoraLdpIT.java
License:asdf
@Test public void testHeadVersionedResourceHeaders() throws IOException { final String subjectURI = createVersionedRDFResource(); try (final CloseableHttpResponse response = execute(new HttpHead(subjectURI))) { verifyVersionedResourceResponseHeaders(subjectURI, response); }//from w w w . j av a 2s. co m }
From source file:org.fcrepo.integration.http.api.FedoraLdpIT.java
License:asdf
@Test public void testBinaryEtags() throws IOException, InterruptedException { final String id = getRandomUniqueId(); createObjectAndClose(id);/*from www.j a va 2 s . c om*/ final String location = serverAddress + id + "/binary"; final HttpPut method = putDSMethod(id, "binary", "foo"); final String binaryEtag1, binaryEtag2, binaryEtag3, descEtag1, descEtag2, descEtag3; final String binaryLastModed1, binaryLastModed2, binaryLastModed3; final String descLastModed1, descLastModed2, descLastModed3; final String descLocation; try (final CloseableHttpResponse response = execute(method)) { binaryEtag1 = response.getFirstHeader("ETag").getValue(); binaryLastModed1 = response.getFirstHeader("Last-Modified").getValue(); descLocation = Link.valueOf(response.getFirstHeader(LINK).getValue()).getUri().toString(); } // First check ETags and Last-Modified headers for the binary final HttpGet get1 = new HttpGet(location); get1.addHeader("If-None-Match", binaryEtag1); assertEquals("Expected 304 Not Modified", NOT_MODIFIED.getStatusCode(), getStatus(get1)); final HttpGet get2 = new HttpGet(location); get2.addHeader("If-Modified-Since", binaryLastModed1); assertEquals("Expected 304 Not Modified", NOT_MODIFIED.getStatusCode(), getStatus(get2)); // Next, check ETags and Last-Modified headers on the description final HttpGet get3 = new HttpGet(descLocation); try (final CloseableHttpResponse response = execute(get3)) { descEtag1 = response.getFirstHeader("ETag").getValue(); descLastModed1 = response.getFirstHeader("Last-Modified").getValue(); } assertNotEquals("Binary, description ETags should be different", binaryEtag1, descEtag1); final HttpGet get4 = new HttpGet(descLocation); get4.addHeader("If-None-Match", descEtag1); assertEquals("Expected 304 Not Modified", NOT_MODIFIED.getStatusCode(), getStatus(get4)); final HttpGet get5 = new HttpGet(descLocation); get5.addHeader("If-Modified-Since", descLastModed1); assertEquals("Expected 304 Not Modified", NOT_MODIFIED.getStatusCode(), getStatus(get5)); // Pause two seconds before updating the description sleep(2000); // Next, update the description final HttpPatch httpPatch = patchObjMethod(id + "/binary/fcr:metadata"); assertTrue("Expected weak ETag", descEtag1.startsWith("W/")); httpPatch.addHeader(CONTENT_TYPE, "application/sparql-update"); httpPatch.addHeader("If-Match", descEtag1.substring(2)); httpPatch.setEntity(new StringEntity( "INSERT { <> <http://purl.org/dc/elements/1.1/title> 'this is a title' } WHERE {}")); assertEquals(NO_CONTENT.getStatusCode(), getStatus(httpPatch)); // Next, check headers for the binary; they should not have changed final HttpHead head1 = new HttpHead(location); try (final CloseableHttpResponse response = execute(head1)) { binaryEtag2 = response.getFirstHeader("ETag").getValue(); binaryLastModed2 = response.getFirstHeader("Last-Modified").getValue(); } assertEquals("ETags should be the same", binaryEtag1, binaryEtag2); assertEquals("Last-Modified should be the same", binaryLastModed1, binaryLastModed2); final HttpGet get6 = new HttpGet(location); get6.addHeader("If-None-Match", binaryEtag1); assertEquals("Expected 304 Not Modified", NOT_MODIFIED.getStatusCode(), getStatus(get6)); final HttpGet get7 = new HttpGet(location); get7.addHeader("If-Modified-Since", binaryLastModed1); assertEquals("Expected 304 Not Modified", NOT_MODIFIED.getStatusCode(), getStatus(get7)); // Next, check headers for the description; they should have changed final HttpHead head2 = new HttpHead(descLocation); try (final CloseableHttpResponse response = execute(head2)) { descEtag2 = response.getFirstHeader("ETag").getValue(); descLastModed2 = response.getFirstHeader("Last-Modified").getValue(); } assertNotEquals("ETags should not be the same", descEtag1, descEtag2); assertNotEquals("Last-Modified should not be the same", descLastModed1, descLastModed2); final HttpGet get8 = new HttpGet(descLocation); get8.addHeader("If-None-Match", descEtag2); assertEquals("Expected 304 Not Modified", NOT_MODIFIED.getStatusCode(), getStatus(get8)); final HttpGet get9 = new HttpGet(descLocation); get9.addHeader("If-Modified-Since", descLastModed2); assertEquals("Expected 304 Not Modified", NOT_MODIFIED.getStatusCode(), getStatus(get9)); sleep(1000); // Next, update the binary itself final HttpPut method2 = new HttpPut(location); assertFalse("Expected strong ETag", binaryEtag1.startsWith("W/")); method2.addHeader("If-Match", binaryEtag1); method2.setEntity(new StringEntity("foobar")); try (final CloseableHttpResponse response = execute(method2)) { assertEquals(NO_CONTENT.getStatusCode(), getStatus(response)); binaryEtag3 = response.getFirstHeader("ETag").getValue(); binaryLastModed3 = response.getFirstHeader("Last-Modified").getValue(); } final HttpGet get10 = new HttpGet(location); get10.addHeader("If-None-Match", binaryEtag1); assertEquals("Expected 200 OK", OK.getStatusCode(), getStatus(get10)); final HttpGet get11 = new HttpGet(location); get11.addHeader("If-Modified-Since", binaryLastModed1); assertEquals("Expected 200 OK", OK.getStatusCode(), getStatus(get11)); assertNotEquals("ETags should have changed", binaryEtag1, binaryEtag3); assertNotEquals("Last-Modified should have changed", binaryLastModed1, binaryLastModed3); // Next, check headers for the description; they should have changed final HttpHead head3 = new HttpHead(descLocation); try (final CloseableHttpResponse response = execute(head3)) { descEtag3 = response.getFirstHeader("ETag").getValue(); descLastModed3 = response.getFirstHeader("Last-Modified").getValue(); } assertNotEquals("ETags should have changed", descEtag2, descEtag3); assertNotEquals("Last-Modified should have changed", descLastModed2, descLastModed3); }
From source file:org.fcrepo.integration.http.api.FedoraLdpIT.java
License:asdf
private void verifyContentDispositionFilename(final String location, final String filename) throws IOException, ParseException { final HttpHead head = new HttpHead(location); try (final CloseableHttpResponse headResponse = execute(head)) { final Header header = headResponse.getFirstHeader(CONTENT_DISPOSITION); assertNotNull(header);/*from w ww . jav a 2 s .c om*/ final ContentDisposition contentDisposition = new ContentDisposition(header.getValue()); assertEquals(filename, contentDisposition.getFileName()); } }
From source file:org.fcrepo.integration.http.api.FedoraLdpIT.java
License:asdf
@Test public void testBinarySetBadMimeType() throws IOException { final String subjectURI = serverAddress + getRandomUniqueId(); final HttpPut createMethod = new HttpPut(subjectURI); createMethod.addHeader(CONTENT_TYPE, "text/plain"); createMethod.setEntity(new StringEntity("Some text here.")); createMethod.addHeader(LINK, NON_RDF_SOURCE_LINK_HEADER); assertEquals(CREATED.getStatusCode(), getStatus(createMethod)); final HttpPatch patch = new HttpPatch(subjectURI + "/fcr:metadata"); patch.addHeader(CONTENT_TYPE, "application/sparql-update"); patch.setEntity(new StringEntity("PREFIX ebucore: <http://www.ebu.ch/metadata/ontologies/ebucore/ebucore#> " + "INSERT { <" + subjectURI + "> ebucore:hasMimeType> \"-- invalid syntax! --\" } WHERE {}")); assertEquals(BAD_REQUEST.getStatusCode(), getStatus(patch)); // make sure it's still retrievable final HttpGet getMethod = new HttpGet(subjectURI); try (final CloseableHttpResponse response = execute(getMethod)) { assertEquals(OK.getStatusCode(), getStatus(response)); final Collection<String> contentTypes = getHeader(response, CONTENT_TYPE); final String contentType = contentTypes.iterator().next(); assertTrue("GET: Expected 'text/plain' instead got: '" + contentType + "'", contentType.contains("text/plain")); }/*from w w w . ja v a 2 s.co m*/ final HttpHead httpHead = new HttpHead(subjectURI); try (final CloseableHttpResponse response = execute(httpHead)) { final Collection<String> contentTypes = getHeader(response, CONTENT_TYPE); final String contentType = contentTypes.iterator().next(); assertTrue("HEAD: Expected 'text/plain' instead got: '" + contentType + "'", contentType.contains("text/plain")); } }
From source file:org.opencastproject.util.HttpUtil.java
/** * Wait for a certain status of a resource. * * @return either an exception or the status code of the last http response *///from ww w. j a v a2s . c o m public static Either<Exception, Integer> waitForResource(final TrustedHttpClient http, final URI resourceUri, final int expectedStatus, final long timeout, final long pollingInterval) { long now = 0L; while (true) { final HttpHead head = new HttpHead(resourceUri); final Either<Exception, Integer> result = http.<Integer>run(head).apply(getStatusCode); for (final Integer status : result.right()) { if (eq(status, expectedStatus) || now >= timeout) { return right(status); } else if (now < timeout) { if (!sleep(pollingInterval)) { return left(new Exception("Interrupted")); } else { now = now + pollingInterval; } } } for (Exception e : result.left()) { return left(e); } } }
From source file:org.rapidoid.http.HttpClient.java
public Future<byte[]> request(String verb, String uri, Map<String, String> headers, Map<String, String> data, Map<String, String> files, byte[] body, String contentType, Callback<byte[]> callback, boolean fullResponse) { headers = U.safe(headers);/*from ww w . ja va2 s. com*/ data = U.safe(data); files = U.safe(files); HttpRequestBase req; boolean canHaveBody = false; if ("GET".equalsIgnoreCase(verb)) { req = new HttpGet(uri); } else if ("DELETE".equalsIgnoreCase(verb)) { req = new HttpDelete(uri); } else if ("OPTIONS".equalsIgnoreCase(verb)) { req = new HttpOptions(uri); } else if ("HEAD".equalsIgnoreCase(verb)) { req = new HttpHead(uri); } else if ("TRACE".equalsIgnoreCase(verb)) { req = new HttpTrace(uri); } else if ("POST".equalsIgnoreCase(verb)) { req = new HttpPost(uri); canHaveBody = true; } else if ("PUT".equalsIgnoreCase(verb)) { req = new HttpPut(uri); canHaveBody = true; } else if ("PATCH".equalsIgnoreCase(verb)) { req = new HttpPatch(uri); canHaveBody = true; } else { throw U.illegalArg("Illegal HTTP verb: " + verb); } for (Entry<String, String> e : headers.entrySet()) { req.addHeader(e.getKey(), e.getValue()); } if (canHaveBody) { HttpEntityEnclosingRequestBase entityEnclosingReq = (HttpEntityEnclosingRequestBase) req; if (body != null) { NByteArrayEntity entity = new NByteArrayEntity(body); if (contentType != null) { entity.setContentType(contentType); } entityEnclosingReq.setEntity(entity); } else { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); for (Entry<String, String> entry : files.entrySet()) { String filename = entry.getValue(); File file = IO.file(filename); builder = builder.addBinaryBody(entry.getKey(), file, ContentType.DEFAULT_BINARY, filename); } for (Entry<String, String> entry : data.entrySet()) { builder = builder.addTextBody(entry.getKey(), entry.getValue(), ContentType.DEFAULT_TEXT); } ByteArrayOutputStream stream = new ByteArrayOutputStream(); try { builder.build().writeTo(stream); } catch (IOException e) { throw U.rte(e); } byte[] bytes = stream.toByteArray(); NByteArrayEntity entity = new NByteArrayEntity(bytes, ContentType.MULTIPART_FORM_DATA); entityEnclosingReq.setEntity(entity); } } Log.debug("Starting HTTP request", "request", req.getRequestLine()); return execute(client, req, callback, fullResponse); }
From source file:org.springframework.http.client.HttpComponentsClientHttpRequestFactory.java
/** * Create a Commons HttpMethodBase object for the given HTTP method and URI specification. * * @param httpMethod the HTTP method//w w w . j a v a 2 s. com * @param uri the URI * @return the Commons HttpMethodBase object */ protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) { switch (httpMethod) { case GET: return new HttpGet(uri); case DELETE: return new HttpDelete(uri); case HEAD: return new HttpHead(uri); case OPTIONS: return new HttpOptions(uri); case POST: return new HttpPost(uri); case PUT: return new HttpPut(uri); case TRACE: return new HttpTrace(uri); default: throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod); } }
From source file:org.structr.rest.common.HttpHelper.java
public static Map<String, String> head(final String address, final String username, final String password, final String proxyUrl, final String proxyUsername, final String proxyPassword, final String cookie, final Map<String, String> headers) { final Map<String, String> responseHeaders = new HashMap<>(); try {/* w w w. j ava 2s . co m*/ final URI url = URI.create(address); final HttpHead req = new HttpHead(url); configure(req, username, password, proxyUrl, proxyUsername, proxyPassword, cookie, headers, false); final CloseableHttpResponse response = client.execute(req); responseHeaders.put("status", Integer.toString(response.getStatusLine().getStatusCode())); for (final Header header : response.getAllHeaders()) { responseHeaders.put(header.getName(), header.getValue()); } } catch (final Throwable t) { logger.error("Unable to get headers from address {}, {}", new Object[] { address, t.getMessage() }); } return responseHeaders; }
From source file:org.talend.components.datastewardship.connection.TdsConnection.java
/** * Checks connection to the host//from w ww . j a v a 2s.c o m * * @return HTTP status code * @throws IOException if host is unreachable */ public int checkConnection() throws IOException { int statusCode = 0; try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpHead httpHead = new HttpHead(hostPort); try (CloseableHttpResponse response = httpClient.execute(httpHead)) { statusCode = response.getStatusLine().getStatusCode(); } } return statusCode; }
From source file:org.wso2.carbon.apimgt.hostobjects.APIProviderHostObject.java
/** * Validate the backend by sending HTTP HEAD * * @param urlVal - backend URL/* w w w. j a va 2 s . c om*/ * @param invalidStatusCodesRegex - Regex for the invalid status code * @return - status of HTTP HEAD Request to backend */ private static NativeObject sendHttpHEADRequest(String urlVal, String invalidStatusCodesRegex) { boolean isConnectionError = true; String response = null; NativeObject data = new NativeObject(); HttpClient client = new DefaultHttpClient(); HttpHead head = new HttpHead(urlVal); client.getParams().setParameter("http.socket.timeout", 4000); client.getParams().setParameter("http.connection.timeout", 4000); if (System.getProperty(APIConstants.HTTP_PROXY_HOST) != null && System.getProperty(APIConstants.HTTP_PROXY_PORT) != null) { if (log.isDebugEnabled()) { log.debug("Proxy configured, hence routing through configured proxy"); } String proxyHost = System.getProperty(APIConstants.HTTP_PROXY_HOST); String proxyPort = System.getProperty(APIConstants.HTTP_PROXY_PORT); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, Integer.parseInt(proxyPort))); } try { HttpResponse httpResponse = client.execute(head); String statusCode = String.valueOf(httpResponse.getStatusLine().getStatusCode()); String reasonPhrase = String.valueOf(httpResponse.getStatusLine().getReasonPhrase()); //If the endpoint doesn't match the regex which specify the invalid status code, it will return success. if (!statusCode.matches(invalidStatusCodesRegex)) { if (log.isDebugEnabled() && statusCode.equals(String.valueOf(HttpStatus.SC_METHOD_NOT_ALLOWED))) { log.debug("Endpoint doesn't support HTTP HEAD"); } response = "success"; isConnectionError = false; } else { //This forms the real backend response to be sent to the client data.put("statusCode", data, statusCode); data.put("reasonPhrase", data, reasonPhrase); response = ""; isConnectionError = false; } } catch (IOException e) { // sending a default error message. log.error("Error occurred while connecting to backend : " + urlVal + ", reason : " + e.getMessage(), e); String[] errorMsg = e.getMessage().split(": "); if (errorMsg.length > 1) { response = errorMsg[errorMsg.length - 1]; //This is to get final readable part of the error message in the exception and send to the client isConnectionError = false; } } finally { client.getConnectionManager().shutdown(); } data.put("response", data, response); data.put("isConnectionError", data, isConnectionError); return data; }