List of usage examples for org.apache.http.client.methods HttpHead HttpHead
public HttpHead(final String uri)
From source file:org.sonatype.nexus.testsuite.security.SimpleSessionCookieIT.java
@Test public void authenticatedContentCRUDActionsShouldNotCreateSession() throws Exception { final String target = resolveUrl(nexusUrl, "content/repositories/releases/test.txt").toExternalForm(); final HttpPut put = new HttpPut(target); put.setEntity(new StringEntity("text content")); try (CloseableHttpClient client = clientBuilder().setDefaultCredentialsProvider(credentialsProvider()) .build()) {/*from ww w . j ava 2s .c om*/ try (CloseableHttpResponse response = client.execute(put, clientContext())) { assertThat(response.getStatusLine().getStatusCode(), is(201)); assertResponseHasNoSessionCookies(response); } } final HttpHead head = new HttpHead(target); try (CloseableHttpClient client = clientBuilder().setDefaultCredentialsProvider(credentialsProvider()) .build()) { try (CloseableHttpResponse response = client.execute(head, clientContext())) { assertThat(response.getStatusLine().getStatusCode(), is(200)); assertResponseHasNoSessionCookies(response); } } final HttpGet get = new HttpGet(target); try (CloseableHttpClient client = clientBuilder().setDefaultCredentialsProvider(credentialsProvider()) .build()) { try (CloseableHttpResponse response = client.execute(get, clientContext())) { assertThat(response.getStatusLine().getStatusCode(), is(200)); assertResponseHasNoSessionCookies(response); } } final HttpDelete delete = new HttpDelete(target); try (CloseableHttpClient client = clientBuilder().setDefaultCredentialsProvider(credentialsProvider()) .build()) { try (CloseableHttpResponse response = client.execute(delete, clientContext())) { assertThat(response.getStatusLine().getStatusCode(), is(204)); assertResponseHasNoSessionCookies(response); } } }
From source file:org.fcrepo.camel.ldpath.FedoraProvider.java
private Header[] getLinkHeaders(final String resourceUri) throws IOException { final HttpHead request = new HttpHead(resourceUri); final HttpResponse response = httpClient.execute(request); LOGGER.debug("Got: " + response.getStatusLine().getStatusCode() + " for HEAD " + resourceUri); return response.getHeaders("Link"); }
From source file:org.craftercms.deployer.impl.processors.HttpMethodCallProcessor.java
protected HttpUriRequest createRequest() { if (method.equalsIgnoreCase("get")) { return new HttpGet(url); } else if (method.equalsIgnoreCase("post")) { return new HttpPost(url); } else if (method.equalsIgnoreCase("put")) { return new HttpPut(url); } else if (method.equalsIgnoreCase("delete")) { return new HttpDelete(url); } else if (method.equalsIgnoreCase("head")) { return new HttpHead(url); } else if (method.equalsIgnoreCase("options")) { return new HttpOptions(url); } else if (method.equalsIgnoreCase("trace")) { return new HttpTrace(url); } else {/*www. j ava 2 s. c o m*/ throw new DeploymentException("HTTP method '" + method + " not recognized"); } }
From source file:org.opencastproject.remotetest.server.DigestAuthenticationTest.java
@Test public void testDigestAuthenticatedPost() throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); // Perform a HEAD, and extract the realm and nonce HttpHead head = new HttpHead(BASE_URL); head.addHeader("X-Requested-Auth", "Digest"); HttpResponse headResponse = httpclient.execute(head); Header authHeader = headResponse.getHeaders("WWW-Authenticate")[0]; String nonce = null;//from ww w.java 2s .c o m String realm = null; for (HeaderElement element : authHeader.getElements()) { if ("nonce".equals(element.getName())) { nonce = element.getValue(); } else if ("Digest realm".equals(element.getName())) { realm = element.getValue(); } } // Build the post UsernamePasswordCredentials creds = new UsernamePasswordCredentials("matterhorn_system_account", "CHANGE_ME"); HttpPost post = new HttpPost(BASE_URL + "/capture-admin/agents/testagent"); post.addHeader("X-Requested-Auth", "Digest"); httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds); List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(); params.add(new BasicNameValuePair("state", "idle")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8"); post.setEntity(entity); // Add the previously obtained nonce HttpContext localContext = new BasicHttpContext(); DigestScheme digestAuth = new DigestScheme(); digestAuth.overrideParamter("realm", realm); digestAuth.overrideParamter("nonce", nonce); localContext.setAttribute("preemptive-auth", digestAuth); // Send the POST try { HttpResponse response = httpclient.execute(post, localContext); String content = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals("testagent set to idle", content); } finally { httpclient.getConnectionManager().shutdown(); } }
From source file:cn.bidaround.ytcore.util.HttpClientStack.java
/** * Creates the appropriate subclass of HttpUriRequest for passed in request. *//* ww w . ja va2 s .com*/ @SuppressWarnings("deprecation") /* protected */ static HttpUriRequest createHttpRequest(Request<?> request, Map<String, String> additionalHeaders) throws AuthFailureError { switch (request.getMethod()) { case Method.DEPRECATED_GET_OR_POST: { // This is the deprecated way that needs to be handled for backwards compatibility. // If the request's post body is null, then the assumption is that the request is // GET. Otherwise, it is assumed that the request is a POST. byte[] postBody = request.getPostBody(); if (postBody != null) { HttpPost postRequest = new HttpPost(request.getUrl()); postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType()); HttpEntity entity; entity = new ByteArrayEntity(postBody); postRequest.setEntity(entity); return postRequest; } else { return new HttpGet(request.getUrl()); } } case Method.GET: return new HttpGet(request.getUrl()); case Method.DELETE: return new HttpDelete(request.getUrl()); case Method.POST: { HttpPost postRequest = new HttpPost(request.getUrl()); postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); setEntityIfNonEmptyBody(postRequest, request); return postRequest; } case Method.PUT: { HttpPut putRequest = new HttpPut(request.getUrl()); putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); setEntityIfNonEmptyBody(putRequest, request); return putRequest; } case Method.HEAD: return new HttpHead(request.getUrl()); case Method.OPTIONS: return new HttpOptions(request.getUrl()); case Method.TRACE: return new HttpTrace(request.getUrl()); case Method.PATCH: { HttpPatch patchRequest = new HttpPatch(request.getUrl()); patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); setEntityIfNonEmptyBody(patchRequest, request); return patchRequest; } default: throw new IllegalStateException("Unknown request method."); } }
From source file:org.elasticsearch.test.rest.client.http.HttpRequestBuilder.java
private HttpUriRequest buildRequest() { if (HttpGetWithEntity.METHOD_NAME.equalsIgnoreCase(method)) { return addOptionalBody(new HttpGetWithEntity(buildUri())); }/* w ww .j ava2 s . co m*/ if (HttpHead.METHOD_NAME.equalsIgnoreCase(method)) { checkBodyNotSupported(); return new HttpHead(buildUri()); } if (HttpDeleteWithEntity.METHOD_NAME.equalsIgnoreCase(method)) { return addOptionalBody(new HttpDeleteWithEntity(buildUri())); } if (HttpPut.METHOD_NAME.equalsIgnoreCase(method)) { return addOptionalBody(new HttpPut(buildUri())); } if (HttpPost.METHOD_NAME.equalsIgnoreCase(method)) { return addOptionalBody(new HttpPost(buildUri())); } throw new UnsupportedOperationException("method [" + method + "] not supported"); }
From source file:com.pmi.restlet.ext.httpclient.internal.HttpMethodCall.java
/** * Constructor.//from ww w .j a v a2 s.c o m * * @param helper * The parent HTTP client helper. * @param method * The method name. * @param requestUri * The request URI. * @param hasEntity * Indicates if the call will have an entity to send to the * server. * @throws IOException */ public HttpMethodCall(HttpClientHelper helper, final String method, final String requestUri, boolean hasEntity) throws IOException { super(helper, method, requestUri); this.clientHelper = helper; if (requestUri.startsWith("http")) { if (method.equalsIgnoreCase(Method.GET.getName())) { this.httpRequest = new HttpGet(requestUri); } else if (method.equalsIgnoreCase(Method.POST.getName())) { this.httpRequest = new HttpPost(requestUri); } else if (method.equalsIgnoreCase(Method.PUT.getName())) { this.httpRequest = new HttpPut(requestUri); } else if (method.equalsIgnoreCase(Method.HEAD.getName())) { this.httpRequest = new HttpHead(requestUri); } else if (method.equalsIgnoreCase(Method.DELETE.getName())) { this.httpRequest = new HttpDelete(requestUri); } else if (method.equalsIgnoreCase(Method.OPTIONS.getName())) { this.httpRequest = new HttpOptions(requestUri); } else if (method.equalsIgnoreCase(Method.TRACE.getName())) { this.httpRequest = new HttpTrace(requestUri); } else { this.httpRequest = new HttpEntityEnclosingRequestBase() { @Override public String getMethod() { return method; } @Override public URI getURI() { try { return new URI(requestUri); } catch (URISyntaxException e) { getLogger().log(Level.WARNING, "Invalid URI syntax", e); return null; } } }; } this.responseHeadersAdded = false; setConfidential(this.httpRequest.getURI().getScheme().equalsIgnoreCase(Protocol.HTTPS.getSchemeName())); } else { throw new IllegalArgumentException("Only HTTP or HTTPS resource URIs are allowed here"); } }
From source file:com.cibuddy.travis.TravisServer.java
/** * /*ww w. j a v a 2s .c o m*/ * @param projectName in case of travis this is called slug ("owner/project") * @param etag if not null, a cache lookup will be done * @return Project state for the Travis hosted project * @throws Exception */ public TravisProjectState getProject(String projectName, String etag) throws Exception { // this assumes the concatination works (might be the source of a bug) String serverURIstring = serveruri.toString(); if (!serverURIstring.endsWith("/")) { serverURIstring = serverURIstring + "/"; } URI u = new URI(serverURIstring + projectName + ".json"); HttpClient httpclient = new DefaultHttpClient(); TravisProjectState bj = jobCache.get(projectName); if (etag != null && bj != null) { // check the cache first HttpHead head = new HttpHead(u); HttpResponse response = httpclient.execute(head); Header h = response.getFirstHeader("Etag"); if (bj.getEtag().equals(h.getValue())) { // we found a cache hit, stop here return bj; } } HttpGet httpget = new HttpGet(u); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); checkResult(response.getStatusLine().getStatusCode()); if (entity != null) { String json = EntityUtils.toString(entity, "utf-8"); TravisProjectState tbp = TravisProjectState.builder(json); if (tbp != null) { Header h = response.getFirstHeader("Etag"); if (h != null && h.getValue() != null) { tbp.setEtag(h.getValue()); jobCache.put(projectName, tbp); } else { LOG.warn( "Something is ODD with the caching mechanism. No Etags are found for results. This is a bug!!!"); } } return tbp; } return null; }
From source file:com.logsniffer.event.publisher.http.HttpPublisher.java
@Override public void publish(final Event event) throws PublishException { VelocityContext vCtx = velocityRenderer.getContext(event); String eventUrl = velocityRenderer.render(url, vCtx); HttpRequestBase request = null;/*from w w w. j ava2 s. c o m*/ switch (method) { case GET: request = new HttpGet(eventUrl); break; case POST: request = new HttpPost(eventUrl); addBody((HttpPost) request, vCtx); break; case PUT: request = new HttpPut(eventUrl); addBody((HttpPut) request, vCtx); break; case DELETE: request = new HttpDelete(eventUrl); break; case HEAD: request = new HttpHead(eventUrl); break; case OPTIONS: request = new HttpOptions(eventUrl); break; case PATCH: request = new HttpPatch(eventUrl); break; case TRACE: request = new HttpTrace(eventUrl); break; } httpAddons(request, event); try { logger.debug("Publishing event {} via HTTP '{}'", event.getId(), request); HttpResponse response = httpClient.execute(request, httpContext); if (response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() < 300) { logger.debug("Published event {} successfuly via HTTP '{}' with status: {}", event.getId(), request, response.getStatusLine().getStatusCode()); } else { logger.warn("Failed to publish event {} via HTTP '{}' due to status: {} - {}", event.getId(), request, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); throw new PublishException("Got errornuous HTTP status for pubslihed event: " + response.getStatusLine().getStatusCode()); } } catch (Exception e) { throw new PublishException("Failed to publish event " + event.getId() + " via HTTP", e); } }
From source file:com.amazonaws.http.ApacheHttpClient.java
private HttpUriRequest createHttpRequest(HttpRequest request) { HttpUriRequest httpRequest;/* www . j a v a 2s . c om*/ String method = request.getMethod(); if (method.equals("POST")) { HttpPost postRequest = new HttpPost(request.getUri()); if (request.getContent() != null) { postRequest.setEntity(new InputStreamEntity(request.getContent(), request.getContentLength())); } httpRequest = postRequest; } else if (method.equals("GET")) { httpRequest = new HttpGet(request.getUri()); } else if (method.equals("PUT")) { HttpPut putRequest = new HttpPut(request.getUri()); if (request.getContent() != null) { putRequest.setEntity(new InputStreamEntity(request.getContent(), request.getContentLength())); } httpRequest = putRequest; } else if (method.equals("DELETE")) { httpRequest = new HttpDelete(request.getUri()); } else if (method.equals("HEAD")) { httpRequest = new HttpHead(request.getUri()); } else { throw new UnsupportedOperationException("Unsupported method: " + method); } if (request.getHeaders() != null && !request.getHeaders().isEmpty()) { for (Map.Entry<String, String> header : request.getHeaders().entrySet()) { String key = header.getKey(); /* * HttpClient4 fills in the Content-Length header and complains * if it's already present, so we skip it here. We also skip the * Host header to avoid sending it twice, which will interfere * with some signing schemes. */ if (key.equals(HttpHeader.CONTENT_LENGTH) || key.equals(HttpHeader.HOST)) { continue; } httpRequest.addHeader(header.getKey(), header.getValue()); } } // disable redirect if (params == null) { params = new BasicHttpParams(); params.setParameter(ClientPNames.HANDLE_REDIRECTS, false); } httpRequest.setParams(params); return httpRequest; }