org.apache.http.client.methods.HttpHead Java Examples
The following examples show how to use
org.apache.http.client.methods.HttpHead.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ApacheHttpRequestFactory.java From aws-sdk-java-v2 with Apache License 2.0 | 7 votes |
private HttpRequestBase createApacheRequest(HttpExecuteRequest request, String uri) { switch (request.httpRequest().method()) { case HEAD: return new HttpHead(uri); case GET: return new HttpGet(uri); case DELETE: return new HttpDelete(uri); case OPTIONS: return new HttpOptions(uri); case PATCH: return wrapEntity(request, new HttpPatch(uri)); case POST: return wrapEntity(request, new HttpPost(uri)); case PUT: return wrapEntity(request, new HttpPut(uri)); default: throw new RuntimeException("Unknown HTTP method name: " + request.httpRequest().method()); } }
Example #2
Source File: RequestUtils.java From RoboZombie with Apache License 2.0 | 6 votes |
/** * <p>Retrieves the proper extension of {@link HttpRequestBase} for the given {@link InvocationContext}. * This implementation is solely dependent upon the {@link RequestMethod} property in the annotated * metdata of the endpoint method definition.</p> * * @param context * the {@link InvocationContext} for which a {@link HttpRequestBase} is to be generated * <br><br> * @return the {@link HttpRequestBase} translated from the {@link InvocationContext}'s {@link RequestMethod} * <br><br> * @throws NullPointerException * if the supplied {@link InvocationContext} was {@code null} * <br><br> * @since 1.3.0 */ static HttpRequestBase translateRequestMethod(InvocationContext context) { RequestMethod requestMethod = Metadata.findMethod(assertNotNull(context).getRequest()); switch (requestMethod) { case POST: return new HttpPost(); case PUT: return new HttpPut(); case PATCH: return new HttpPatch(); case DELETE: return new HttpDelete(); case HEAD: return new HttpHead(); case TRACE: return new HttpTrace(); case OPTIONS: return new HttpOptions(); case GET: default: return new HttpGet(); } }
Example #3
Source File: MartiDiceRoller.java From triplea with GNU General Public License v3.0 | 6 votes |
@Override public HttpUriRequest getRedirect( final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException { final URI uri = getLocationURI(request, response, context); final String method = request.getRequestLine().getMethod(); if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) { return new HttpHead(uri); } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) { return new HttpGet(uri); } else { final int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_TEMPORARY_REDIRECT || status == HttpStatus.SC_MOVED_PERMANENTLY || status == HttpStatus.SC_MOVED_TEMPORARILY) { return RequestBuilder.copy(request).setUri(uri).build(); } return new HttpGet(uri); } }
Example #4
Source File: ApacheHttpRequestFactory.java From ibm-cos-sdk-java with Apache License 2.0 | 6 votes |
private HttpRequestBase createApacheRequest(Request<?> request, String uri, String encodedParams) throws FakeIOException { switch (request.getHttpMethod()) { case HEAD: return new HttpHead(uri); case GET: return new HttpGet(uri); case DELETE: return new HttpDelete(uri); case OPTIONS: return new HttpOptions(uri); case PATCH: return wrapEntity(request, new HttpPatch(uri), encodedParams); case POST: return wrapEntity(request, new HttpPost(uri), encodedParams); case PUT: return wrapEntity(request, new HttpPut(uri), encodedParams); default: throw new SdkClientException("Unknown HTTP method name: " + request.getHttpMethod()); } }
Example #5
Source File: MockedClientTests.java From ibm-cos-sdk-java with Apache License 2.0 | 6 votes |
/** * Response to HEAD requests don't have an entity so we shouldn't try to wrap the response in a * {@link BufferedHttpEntity}. */ @Test public void requestTimeoutEnabled_HeadRequestCompletesWithinTimeout_EntityNotBuffered() throws Exception { ClientConfiguration config = new ClientConfiguration().withRequestTimeout(5 * 1000).withMaxErrorRetry(0); ConnectionManagerAwareHttpClient rawHttpClient = createRawHttpClientSpy(config); HttpResponseProxy responseProxy = createHttpHeadResponseProxy(); doReturn(responseProxy).when(rawHttpClient).execute(any(HttpHead.class), any(HttpContext.class)); httpClient = new AmazonHttpClient(config, rawHttpClient, null); try { execute(httpClient, createMockHeadRequest()); fail("Exception expected"); } catch (AmazonClientException e) { NullResponseHandler.assertIsUnmarshallingException(e); } assertNull(responseProxy.getEntity()); }
Example #6
Source File: PluginManagerTest.java From plugin-installation-manager-tool with MIT License | 6 votes |
@Test public void checkVersionSpecificUpdateCenterTest() throws Exception { //Test where version specific update center exists pm.setJenkinsVersion(new VersionNumber("2.176")); mockStatic(HttpClients.class); CloseableHttpClient httpclient = mock(CloseableHttpClient.class); when(HttpClients.createSystem()).thenReturn(httpclient); HttpHead httphead = mock(HttpHead.class); whenNew(HttpHead.class).withAnyArguments().thenReturn(httphead); CloseableHttpResponse response = mock(CloseableHttpResponse.class); when(httpclient.execute(httphead)).thenReturn(response); StatusLine statusLine = mock(StatusLine.class); when(response.getStatusLine()).thenReturn(statusLine); int statusCode = HttpStatus.SC_OK; when(statusLine.getStatusCode()).thenReturn(statusCode); pm.checkAndSetLatestUpdateCenter(); String expected = dirName(cfg.getJenkinsUc()) + pm.getJenkinsVersion() + Settings.DEFAULT_UPDATE_CENTER_FILENAME; assertEquals(expected, pm.getJenkinsUCLatest()); }
Example #7
Source File: HttpComponentsClientHttpRequestFactory.java From spring4-understanding with Apache License 2.0 | 6 votes |
/** * 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 HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) { switch (httpMethod) { case GET: return new HttpGet(uri); case HEAD: return new HttpHead(uri); case POST: return new HttpPost(uri); case PUT: return new HttpPut(uri); case PATCH: return new HttpPatch(uri); case DELETE: return new HttpDelete(uri); case OPTIONS: return new HttpOptions(uri); case TRACE: return new HttpTrace(uri); default: throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod); } }
Example #8
Source File: HeadTestCase.java From quarkus-http with Apache License 2.0 | 6 votes |
@Test public void sendHttpHead() throws IOException { HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path"); HttpHead head = new HttpHead(DefaultServer.getDefaultServerURL() + "/path"); TestHttpClient client = new TestHttpClient(); try { generateMessage(1); HttpResponse result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); Assert.assertEquals(message, HttpClientUtils.readResponse(result)); result = client.execute(head); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); Assert.assertEquals("", HttpClientUtils.readResponse(result)); generateMessage(1000); result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); Assert.assertEquals(message, HttpClientUtils.readResponse(result)); result = client.execute(head); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); Assert.assertEquals("", HttpClientUtils.readResponse(result)); } finally { client.getConnectionManager().shutdown(); } }
Example #9
Source File: HttpComponentsClientHttpRequestFactory.java From spring-analysis-note with MIT License | 6 votes |
/** * 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 HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) { switch (httpMethod) { case GET: return new HttpGet(uri); case HEAD: return new HttpHead(uri); case POST: return new HttpPost(uri); case PUT: return new HttpPut(uri); case PATCH: return new HttpPatch(uri); case DELETE: return new HttpDelete(uri); case OPTIONS: return new HttpOptions(uri); case TRACE: return new HttpTrace(uri); default: throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod); } }
Example #10
Source File: HttpClientHandler.java From ant-ivy with Apache License 2.0 | 6 votes |
private boolean checkStatusCode(final String httpMethod, final URL sourceURL, final HttpResponse response) { final int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_OK) { return true; } // IVY-1328: some servers return a 204 on a HEAD request if (HttpHead.METHOD_NAME.equals(httpMethod) && (status == 204)) { return true; } Message.debug("HTTP response status: " + status + " url=" + sourceURL); if (status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) { Message.warn("Your proxy requires authentication."); } else if (String.valueOf(status).startsWith("4")) { Message.verbose("CLIENT ERROR: " + response.getStatusLine().getReasonPhrase() + " url=" + sourceURL); } else if (String.valueOf(status).startsWith("5")) { Message.error("SERVER ERROR: " + response.getStatusLine().getReasonPhrase() + " url=" + sourceURL); } return false; }
Example #11
Source File: HttpClientTests.java From vividus with Apache License 2.0 | 6 votes |
@Test void testDoHttpHeadContext() throws Exception { CloseableHttpResponse closeableHttpResponse = mock(CloseableHttpResponse.class); HttpContext context = mock(HttpContext.class); when(closeableHttpResponse.getEntity()).thenReturn(null); StatusLine statusLine = mock(StatusLine.class); int statusCode = HttpStatus.SC_MOVED_PERMANENTLY; Header[] headers = { header }; when(closeableHttpResponse.getAllHeaders()).thenReturn(headers); when(statusLine.getStatusCode()).thenReturn(statusCode); when(closeableHttpResponse.getStatusLine()).thenReturn(statusLine); when(closeableHttpClient.execute(isA(HttpHead.class), eq(context))) .thenAnswer(getAnswerWithSleep(closeableHttpResponse)); HttpResponse httpResponse = httpClient.doHttpHead(URI_TO_GO, context); assertEquals(HEAD, httpResponse.getMethod()); assertEquals(URI_TO_GO, httpResponse.getFrom()); assertEquals(statusCode, httpResponse.getStatusCode()); assertThat(httpResponse.getResponseTimeInMs(), greaterThan(0L)); assertThat(httpResponse.getResponseHeaders(), is(equalTo(headers))); }
Example #12
Source File: HttpClientStackTest.java From device-database with Apache License 2.0 | 5 votes |
@Test public void createHeadRequest() throws Exception { TestRequest.Head request = new TestRequest.Head(); assertEquals(request.getMethod(), Method.HEAD); HttpUriRequest httpRequest = HttpClientStack.createHttpRequest(request, null); assertTrue(httpRequest instanceof HttpHead); }
Example #13
Source File: HttpClientHandler.java From ant-ivy with Apache License 2.0 | 5 votes |
private CloseableHttpResponse doHead(final URL url, final int connectionTimeout, final int readTimeout) throws IOException { final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeout) .setConnectTimeout(connectionTimeout) .setAuthenticationEnabled(hasCredentialsConfigured(url)) .setTargetPreferredAuthSchemes(getAuthSchemePreferredOrder()) .setProxyPreferredAuthSchemes(getAuthSchemePreferredOrder()) .build(); final HttpHead httpHead = new HttpHead(normalizeToString(url)); httpHead.setConfig(requestConfig); return this.httpClient.execute(httpHead); }
Example #14
Source File: ESBJAVA1897HttpHeadMethodTestCase.java From micro-integrator with Apache License 2.0 | 5 votes |
@Test(groups = "wso2.esb", description = "test to verify that the HTTP HEAD method works with PTT.") public void testHttpHeadMethod() throws Exception { String restURL = (getProxyServiceURLHttp(SERVICE_NAME)) + "/students"; DefaultHttpClient httpclient = new DefaultHttpClient(); HttpHead httpHead = new HttpHead(restURL); HttpResponse response = httpclient.execute(httpHead); // http head method should return a 202 Accepted assertTrue(response.getStatusLine().getStatusCode() == 202); // it should not contain a message body assertTrue(response.getEntity() == null); }
Example #15
Source File: HeadIT.java From wisdom with Apache License 2.0 | 5 votes |
@Test public void testHeadToGetSwitchOnMissingPage() throws Exception { HttpHead head = new HttpHead(getHttpURl("/hello/missing")); HttpResponse<String> response; try { org.apache.http.HttpResponse resp = ClientFactory.getHttpClient().execute(head); response = new HttpResponse<>(resp, String.class); } finally { head.releaseConnection(); } assertThat(response.code()).isEqualTo(NOT_FOUND); assertThat(response.body()).isNull(); }
Example #16
Source File: HttpClientStackTest.java From volley with Apache License 2.0 | 5 votes |
@Test public void createHeadRequest() throws Exception { TestRequest.Head request = new TestRequest.Head(); assertEquals(request.getMethod(), Method.HEAD); HttpUriRequest httpRequest = HttpClientStack.createHttpRequest(request, null); assertTrue(httpRequest instanceof HttpHead); }
Example #17
Source File: HttpClient.java From ats-framework with Apache License 2.0 | 5 votes |
/** * Invoke the endpoint URL using a HTTP HEAD. * * @return The response * @throws HttpException */ @PublicAtsApi public HttpResponse head() throws HttpException { final URI uri = constructURI(); HttpHead method = new HttpHead(uri); log.info("We will run a HEAD request from " + uri); return execute(method); }
Example #18
Source File: BasicHttpTest.java From cloud-odata-java with Apache License 2.0 | 5 votes |
@Test public void unsupportedMethod() throws Exception { HttpResponse response = getHttpClient().execute(new HttpHead(getEndpoint())); assertEquals(HttpStatusCodes.NOT_IMPLEMENTED.getStatusCode(), response.getStatusLine().getStatusCode()); response = getHttpClient().execute(new HttpOptions(getEndpoint())); assertEquals(HttpStatusCodes.NOT_IMPLEMENTED.getStatusCode(), response.getStatusLine().getStatusCode()); }
Example #19
Source File: DefaultDispatch.java From knox with Apache License 2.0 | 5 votes |
@Override public void doHead(URI url, HttpServletRequest request, HttpServletResponse response) throws IOException { final HttpHead method = new HttpHead(url); copyRequestHeaderFields(method, request); executeRequest(method, request, response); }
Example #20
Source File: ESBJAVA1897HttpHeadMethodTestCase.java From product-ei with Apache License 2.0 | 5 votes |
@Test(groups = "wso2.esb", description = "test to verify that the HTTP HEAD method works with PTT.") public void testHttpHeadMethod() throws Exception { String restURL = (getProxyServiceURLHttp(SERVICE_NAME)) + "/students"; DefaultHttpClient httpclient = new DefaultHttpClient(); HttpHead httpHead = new HttpHead(restURL); HttpResponse response = httpclient.execute(httpHead); // http head method should return a 202 Accepted assertTrue(response.getStatusLine().getStatusCode() == 202); // it should not contain a message body assertTrue(response.getEntity() == null); }
Example #21
Source File: NistMirrorTask.java From dependency-track with Apache License 2.0 | 5 votes |
/** * Performs a HTTP HEAD request to determine if a URL has updates since the last * time it was requested. * @param cveUrl the URL to perform a HTTP HEAD request on * @return the length of the content if it were to be downloaded */ private long checkHead(final String cveUrl) { final HttpUriRequest request = new HttpHead(cveUrl); try (final CloseableHttpResponse response = HttpClientPool.getClient().execute(request)) { return Long.valueOf(response.getFirstHeader(HttpHeaders.CONTENT_LENGTH).getValue()); } catch (IOException | NumberFormatException | NullPointerException e) { LOGGER.error("Failed to determine content length"); } return 0; }
Example #22
Source File: HttpUtils.java From PracticeDemo with Apache License 2.0 | 5 votes |
/** * 可以提前获取网页的 statusCode 如200 404 * Notice 需要异步 * @param url 网页的url * @return statusCode 默认-1 */ public static int getPageStatusCode(String url) { int status = -1; try { HttpHead head = new HttpHead(url); HttpClient client = new DefaultHttpClient(); HttpResponse resp = client.execute(head); status = resp.getStatusLine().getStatusCode(); } catch (IOException e) { e.printStackTrace(); } return status; }
Example #23
Source File: HttpRequest.java From blueocean-plugin with MIT License | 5 votes |
public HttpResponse head(String url) { try { return new HttpResponse(client.execute(setAuthorizationHeader(new HttpHead(url)))); } catch (IOException e) { throw handleException(e); } }
Example #24
Source File: MavenRepositoryDeployer.java From maven-repository-tools with Eclipse Public License 1.0 | 5 votes |
/** * Check if POM file for provided gav can be found in target. Just does * a HTTP get of the header and verifies http status OK 200. * @param targetUrl url of the target repository * @param gav group artifact version string * @return {@code true} if the pom.xml already exists in the target repository */ private boolean checkIfPomInTarget( String targetUrl, String username, String password, Gav gav ) { boolean alreadyInTarget = false; String artifactUrl = targetUrl + gav.getRepositoryURLPath() + gav.getPomFilename(); logger.debug( "Headers for {}", artifactUrl ); HttpHead httphead = new HttpHead( artifactUrl ); if ( !StringUtils.isEmpty( username ) && ! StringUtils.isEmpty( password ) ) { String encoding = java.util.Base64.getEncoder().encodeToString( ( username + ":" + password ).getBytes() ); httphead.setHeader( "Authorization", "Basic " + encoding ); } try ( CloseableHttpClient httpClient = HttpClientBuilder.create().build() ) { HttpResponse response = httpClient.execute( httphead ); int statusCode = response.getStatusLine().getStatusCode(); if ( statusCode == HttpURLConnection.HTTP_OK ) { alreadyInTarget = true; } else { logger.debug( "Headers not found HTTP: {}", statusCode ); } } catch ( IOException ioe ) { logger.warn( "Could not check target repository for already existing pom.xml.", ioe ); } return alreadyInTarget; }
Example #25
Source File: ApacheHttpRequest.java From junit-servers with MIT License | 5 votes |
HttpRequestBase create(HttpMethod httpMethod) { if (httpMethod == HttpMethod.GET) { return new HttpGet(); } if (httpMethod == HttpMethod.POST) { return new HttpPost(); } if (httpMethod == HttpMethod.PUT) { return new HttpPut(); } if (httpMethod == HttpMethod.DELETE) { return new HttpDelete(); } if (httpMethod == HttpMethod.PATCH) { return new HttpPatch(); } if (httpMethod == HttpMethod.HEAD) { return new HttpHead(); } throw new UnsupportedOperationException("Method " + httpMethod + " is not supported by apache http-client"); }
Example #26
Source File: AbstractSingleCheckThread.java From sitemonitoring-production with BSD 3-Clause "New" or "Revised" License | 5 votes |
protected CloseableHttpResponse doHead(final String url) throws IOException { HttpHead request = new HttpHead(url); // optimization if (isVisitedPageHead(request.getURI())) { log.debug("page already visited, won't visit again"); return null; } else { addVisitedPageHead(request.getURI()); } return doRequest(request); }
Example #27
Source File: HttpClientPerformanceTest.java From keycloak with Apache License 2.0 | 5 votes |
public CustomRedirectStrategy() { this.REDIRECT_METHODS = new String[]{ HttpGet.METHOD_NAME, HttpPost.METHOD_NAME, HttpHead.METHOD_NAME, HttpDelete.METHOD_NAME, HttpOptions.METHOD_NAME }; }
Example #28
Source File: Http4FileObject.java From commons-vfs with Apache License 2.0 | 5 votes |
@Override protected FileType doGetType() throws Exception { lastHeadResponse = executeHttpUriRequest(new HttpHead(getInternalURI())); final int status = lastHeadResponse.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_OK || status == HttpStatus.SC_METHOD_NOT_ALLOWED /* method is not allowed, but resource exist */) { return FileType.FILE; } else if (status == HttpStatus.SC_NOT_FOUND || status == HttpStatus.SC_GONE) { return FileType.IMAGINARY; } else { throw new FileSystemException("vfs.provider.http/head.error", getName(), Integer.valueOf(status)); } }
Example #29
Source File: SolrCLI.java From lucene-solr with Apache License 2.0 | 5 votes |
/** * Tries a simple HEAD request and throws SolrException in case of Authorization error * @param url the url to do a HEAD request to * @param httpClient the http client to use (make sure it has authentication optinos set) * @return the HTTP response code * @throws SolrException if auth/autz problems * @throws IOException if connection failure */ private static int attemptHttpHead(String url, HttpClient httpClient) throws SolrException, IOException { HttpResponse response = httpClient.execute(new HttpHead(url), HttpClientUtil.createNewHttpClientRequestContext()); int code = response.getStatusLine().getStatusCode(); if (code == UNAUTHORIZED.code || code == FORBIDDEN.code) { throw new SolrException(SolrException.ErrorCode.getErrorCode(code), "Solr requires authentication for " + url + ". Please supply valid credentials. HTTP code=" + code); } return code; }
Example #30
Source File: Rest.java From components with Apache License 2.0 | 5 votes |
/** * Checks connection to the host * * @return HTTP status code * @throws IOException if host is unreachable */ public int checkConnection() throws IOException { int statusCode = 0; try (CloseableHttpClient httpClient = createHttpClient()) { HttpHead httpHead = new HttpHead(hostPort); try (CloseableHttpResponse response = httpClient.execute(httpHead)) { statusCode = response.getStatusLine().getStatusCode(); } } return statusCode; }