Example usage for org.apache.http.client.methods HttpHead HttpHead

List of usage examples for org.apache.http.client.methods HttpHead HttpHead

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpHead HttpHead.

Prototype

public HttpHead(final String uri) 

Source Link

Usage

From source file:org.wymiwyg.wrhapi.test.BaseTests.java

@Test
public void testStatusCodeResetInMessageBody() throws Exception {
    final int newStatusCode = 302;
    WebServer webServer = createServer().startNewWebServer(new Handler() {

        public void handle(Request request, final Response response) throws HandlerException {
            log.info("handling testStatusCode");
            response.setResponseStatus(ResponseStatus.CREATED);
            response.setHeader(HeaderName.SERVER, "Ad-Hoc testing server");
            response.setHeader(HeaderName.LOCATION, "http://example.org");
            response.setBody(new MessageBody2Write() {

                public void writeTo(WritableByteChannel out) throws IOException {
                    try {
                        response.setResponseStatus(ResponseStatus.getInstanceByCode(newStatusCode));
                    } catch (HandlerException ex) {
                        throw new RuntimeException(ex);
                    }//from w  w  w .  j  av  a2s  .c o m
                    ByteBuffer bb = ByteBuffer.wrap("this is the body".getBytes());
                    out.write(bb);
                }
            });
        }
    }, serverBinding);

    try {
        URI serverURL = new URI("http://" + serverBinding.getInetAddress().getHostAddress() + ":"
                + serverBinding.getPort() + "/");
        HttpHead method = new HttpHead(serverURL);
        DefaultHttpClient client = new DefaultHttpClient();
        client.setHttpRequestRetryHandler(null);
        client.setRedirectHandler(nullRedirectHandler);
        HttpResponse response = client.execute(method);
        // for the handler to be invoked, something of the response has to
        // be asked
        assertEquals(newStatusCode, response.getStatusLine().getStatusCode());
    } finally {
        webServer.stop();
    }
}

From source file:org.coronastreet.gpxconverter.GarminForm.java

protected boolean doLogin() {
    boolean ret = false;
    log("Authenticating athlete...");

    String gauthURL = "https://sso.garmin.com/sso/login?service=http%3A%2F%2Fconnect.garmin.com%2Fpost-auth%2Flogin&webhost=olaxpw-connect07.garmin.com&source=http%3A%2F%2Fconnect.garmin.com%2Fde-DE%2Fsignin&redirectAfterAccountLoginUrl=http%3A%2F%2Fconnect.garmin.com%2Fpost-auth%2Flogin&redirectAfterAccountCreationUrl=http%3A%2F%2Fconnect.garmin.com%2Fpost-auth%2Flogin&gauthHost=https%3A%2F%2Fsso.garmin.com%2Fsso&locale=de&id=gauth-widget&cssUrl=https%3A%2F%2Fstatic.garmincdn.com%2Fcom.garmin.connect%2Fui%2Fsrc-css%2Fgauth-custom.css&clientId=GarminConnect&rememberMeShown=true&rememberMeChecked=false&createAccountShown=true&openCreateAccount=false&usernameShown=true&displayNameShown=false&consumeServiceTicket=false&initialFocus=true&embedWidget=false";
    try {//from ww w  .  j av  a2 s . c om
        HttpGet get = new HttpGet(gauthURL);
        HttpResponse formResponse = httpClient.execute(get, localContext);
        //log("Fetched the gauth url...: " + formResponse.getStatusLine());
        String out = EntityUtils.toString(formResponse.getEntity());
        org.jsoup.nodes.Document doc = Jsoup.parse(out);
        //System.out.println("RAW:\n" + out);
        String flowKey = findFlowKey(doc);
        //log("Looks like our Key is " + flowKey);

        HttpPost post = new HttpPost(gauthURL);
        post.setHeader("Referer", "https://sso.garmin.com/sso/login");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("lt", flowKey));
        nvps.add(new BasicNameValuePair("embed", "true"));
        nvps.add(new BasicNameValuePair("username", GPXConverter.getPref("garmin_username")));
        nvps.add(new BasicNameValuePair("password",
                AccountManager.decrypt(GPXConverter.getPref("garmin_password"))));
        nvps.add(new BasicNameValuePair("_eventId", "submit"));

        post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        HttpResponse sessionResponse = httpClient.execute(post, localContext);

        String output = EntityUtils.toString(sessionResponse.getEntity());
        Pattern ticketPattern = Pattern.compile("= '(http.*ticket=.*)';");
        Matcher m = ticketPattern.matcher(output);
        String ticketURL = null;
        while (m.find()) {
            ticketURL = m.group(1);
        }
        //log("Ticket? " + ticketURL);
        HttpEntity entity = sessionResponse.getEntity();
        EntityUtils.consume(entity);

        HttpHead head = new HttpHead(ticketURL);
        HttpResponse headResponse = httpClient.execute(head, localContext);

        if (headResponse.getStatusLine().getStatusCode() == 200) {
            ret = true;
        }
        HttpEntity ent = headResponse.getEntity();
        EntityUtils.consume(ent);

    } catch (Exception e) {
        e.printStackTrace();
    }

    return ret;
}

From source file:com.hoccer.tools.HttpHelper.java

public static boolean isReachable(String pUri) {

    HttpHead head = new HttpHead(pUri);
    try {/*  ww w . java 2 s  . co  m*/
        executeHTTPMethod(head);
    } catch (HttpException e) {
        return false;
    } catch (IOException e) {
        return false;
    }

    return true;
}

From source file:com.mobiperf.speedometer.measurements.PingTask.java

/**
 * Use the HTTP Head method to emulate ping. The measurement from this method can be substantially
 * (2x) greater than the first two methods and inaccurate. This is because, depending on the
 * implementing of the destination web server, either a quick HTTP response is replied or some
 * actual heavy lifting will be done in preparing the response
 * *//*  w w w .  j  ava  2  s .c  o  m*/
private MeasurementResult executeHttpPingTask() throws MeasurementError {
    long pingStartTime = 0;
    long pingEndTime = 0;
    ArrayList<Double> rrts = new ArrayList<Double>();
    PingDesc pingTask = (PingDesc) this.measurementDesc;
    String errorMsg = "";
    MeasurementResult result = null;

    try {
        long totalPingDelay = 0;

        HttpClient client = AndroidHttpClient.newInstance(Util.prepareUserAgent(this.parent));
        HttpHead headMethod;

        headMethod = new HttpHead("http://" + targetIp);

        headMethod.addHeader(new BasicHeader("Connection", "close"));
        headMethod.setParams(new BasicHttpParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000));

        int timeOut = (int) (1000 * (double) pingTask.pingTimeoutSec / Config.PING_COUNT_PER_MEASUREMENT);
        HttpConnectionParams.setConnectionTimeout(headMethod.getParams(), timeOut);

        for (int i = 0; i < Config.PING_COUNT_PER_MEASUREMENT; i++) {
            pingStartTime = System.currentTimeMillis();
            HttpResponse response = client.execute(headMethod);
            pingEndTime = System.currentTimeMillis();
            rrts.add((double) (pingEndTime - pingStartTime));
            this.progress = 100 * i / Config.PING_COUNT_PER_MEASUREMENT;
            broadcastProgressForUser(progress);
        }
        Logger.i("HTTP get ping succeeds");
        double packetLoss = 1 - ((double) rrts.size() / (double) Config.PING_COUNT_PER_MEASUREMENT);
        result = constructResult(rrts, packetLoss, Config.PING_COUNT_PER_MEASUREMENT);
        // close the client to avoid memory leak
        ((AndroidHttpClient) client).close();
    } catch (MalformedURLException e) {
        Logger.e(e.getMessage());
        errorMsg += e.getMessage() + "\n";
    } catch (IOException e) {
        Logger.e(e.getMessage());
        errorMsg += e.getMessage() + "\n";
    }
    if (result != null) {
        return result;
    } else {
        Logger.i("HTTP get ping fails");
        throw new MeasurementError(errorMsg);
    }
}

From source file:com.github.restdriver.clientdriver.integration.ClientDriverSuccessTest.java

@Test
public void testHttpHEADMatchesHttpGETExceptForEntity() throws Exception {

    String baseUrl = driver.getBaseUrl();
    String URL = baseUrl + "/blah2";

    driver.addExpectation(onRequestTo("/blah2").withMethod(Method.GET),
            giveResponse("something", "text/plain").withStatus(200).withHeader("Allow", "GET, HEAD"));
    driver.addExpectation(onRequestTo("/blah2").withMethod(Method.HEAD),
            giveResponse("something", "text/plain").withStatus(200).withHeader("Allow", "GET, HEAD"));

    HttpClient client = new DefaultHttpClient();

    HttpHead headRequest = new HttpHead(URL);
    HttpResponse headResponse = client.execute(headRequest);

    HttpGet getRequest = new HttpGet(URL);
    HttpResponse getResponse = client.execute(getRequest);

    assertThat(headResponse.getStatusLine().getStatusCode(), is(200));
    assertThat(headResponse.getHeaders("Allow")[0].getValue(), equalTo("GET, HEAD"));
    assertThat(headResponse.getAllHeaders().length, is(getResponse.getAllHeaders().length));

    String getEntityBody = EntityUtils.toString(getResponse.getEntity());
    assertThat(getEntityBody, is("something"));

    assertThat(headResponse.getEntity(), nullValue());
}

From source file:com.archivas.clienttools.arcutils.impl.adapter.Hcp3AuthNamespaceAdapter.java

/**
 * The Metadata we collect from the Authenticated Namespace is as follows: index, shred,
 * retention (class or value), hold We collect DPL and Hash algorithm for display reasons, but
 * these will always get the target default when we are moving them We do not collect POSIX
 * values for the Authenticated namespace
 * /*w  ww . jav  a2s .  c o m*/
 * @inheritDoc
 */
public FileMetadata getMetadata(String filePath, final String queryString, FileType unused, boolean isVersion)
        throws StorageAdapterException {

    FileMetadata metadata = null;

    HttpHost httpHost = new HttpHost(getHost(), profile.getPort(), profile.getProtocol());
    String urlPath = filePath;

    if (queryString != null) {
        urlPath = urlPath + queryString;
    }
    HttpUriRequest request = new HttpHead(getProfile().resolvePath(urlPath));

    try {
        // Eventually we will just return this cookie which will be passed back to the caller.
        HcapAdapterCookie cookie = new HcapAdapterCookie(request, httpHost);
        synchronized (savingCookieLock) {
            if (savedCookie != null) {
                throw new RuntimeException(
                        "This adapter already has a current connection to host -- cannot create two at once.");
            }
            savedCookie = cookie;
        }
        executeMethod(cookie);
        this.handleHttpResponse(cookie.getResponse(), "getting metadata", filePath);

        Header headers[] = cookie.getResponse().getAllHeaders();
        String symlinkTarget = null;
        for (Header h : headers) {
            if (HttpGatewayConstants.HEADER_LINK_ANS.equals(h.getName())) {
                symlinkTarget = h.getValue();
            }
        }

        // resultType indicates what is returned:
        String responseTypeStr = cookie.getResponse().getFirstHeader(HttpGatewayConstants.HEADER_OBJ_TYPE_ANS)
                .getValue();
        FileType responseType = "object".equals(responseTypeStr) ? FileType.FILE : FileType.DIRECTORY;
        FileType fileType = responseType;
        if (symlinkTarget != null) {
            // if there is a symlink target, then the FileType is symlink. The symlink can be a
            // link to a directory or
            // a link to a file.
            fileType = FileType.SYMLINK;
        }
        if (responseType == FileType.DIRECTORY) {
            // no additional metadata for directories
            metadata = new FileMetadata(fileType);
        } else if (responseType == FileType.FILE) {
            long size = Long.parseLong(
                    cookie.getResponse().getFirstHeader(HttpGatewayConstants.HEADER_OBJ_SIZE_ANS).getValue());
            long version = Long.parseLong(cookie.getResponse()
                    .getFirstHeader(HttpGatewayConstants.HEADER_OBJ_VERSION_ANS).getValue());
            String ingestTimeString = cookie.getResponse()
                    .getFirstHeader(HttpGatewayConstants.HEADER_OBJ_CREATE_TIME_ANS).getValue();
            Date ingestTime = (ingestTimeString == null ? null
                    : new Date(Long.parseLong(ingestTimeString) * 1000));
            boolean retentionHold = Boolean.parseBoolean(cookie.getResponse()
                    .getFirstHeader(HttpGatewayConstants.HEADER_RETENTION_HOLD_BOOLEAN_ANS).getValue());
            boolean shred = Boolean.parseBoolean(cookie.getResponse()
                    .getFirstHeader(HttpGatewayConstants.HEADER_SHRED_BOOLEAN_ANS).getValue());
            int dpl = Integer.parseInt(
                    cookie.getResponse().getFirstHeader(HttpGatewayConstants.HEADER_DPL_VALUE_ANS).getValue());
            boolean searchIndex = Boolean.parseBoolean(cookie.getResponse()
                    .getFirstHeader(HttpGatewayConstants.HEADER_INDEX_VALUE_ANS).getValue());

            // >= 4.0 value. Need to test for null
            Boolean replicated = null;
            try {
                replicated = Boolean.parseBoolean(cookie.getResponse()
                        .getFirstHeader(HttpGatewayConstants.HEADER_REPLICATED_CSL_ANS).getValue());
            } catch (NullPointerException e) {
                /* We don't do anything */ }

            boolean hasCustomMetadata = Boolean.parseBoolean(cookie.getResponse()
                    .getFirstHeader(HttpGatewayConstants.HEADER_CUST_METADATA_BOOLEAN_ANS).getValue());
            CustomMetadata customMetadata = null;
            if (hasCustomMetadata) {
                customMetadata = new CustomMetadata(CustomMetadata.Form.PROFILED, filePath,
                        isVersion ? version : null);
            }

            // Retention on the auth namespace either comes back with a class, a value or a
            // string (deletion
            // prohibited, etc.) So we have to construct the rentention object here
            // appropriately
            String retentionClass = null;
            Long retentionValue = null;
            String retentionString = null;
            try {
                retentionClass = cookie.getResponse()
                        .getFirstHeader(HttpGatewayConstants.HEADER_RETENTION_CLASS_ANS).getValue();
            } catch (NullPointerException e) {
                // do nothing
            }
            try {
                retentionValue = Long.parseLong(cookie.getResponse()
                        .getFirstHeader(HttpGatewayConstants.HEADER_RETENTION_LONG_TIME_ANS).getValue());
            } catch (NullPointerException e) {
                // do nothing
            }
            try {
                retentionString = cookie.getResponse()
                        .getFirstHeader(HttpGatewayConstants.HEADER_RETENTION_STRING_TIME_ANS).getValue();
            } catch (NullPointerException e) {
                // do nothing
            }
            if (retentionString != null && !retentionString.equals("")) {
                if (retentionString.equals(Retention.DELETION_ALLOWED.getUIValue())) {
                    retentionValue = Long.parseLong(Retention.DELETION_ALLOWED.getHCAPValue());
                } else if (retentionString.equals(Retention.DELETION_PROHIBITED.getUIValue())) {
                    retentionValue = Long.parseLong(Retention.DELETION_PROHIBITED.getHCAPValue());
                } else if (retentionString.equals(Retention.INITIAL_UNSPECIFIED.getUIValue())) {
                    retentionValue = Long.parseLong(Retention.INITIAL_UNSPECIFIED.getHCAPValue());
                }
            }
            Retention retention = Retention.fromRetentionValueAndClass(retentionValue, retentionClass);

            String hash = "";
            String hashScheme = "";
            String hashValue = "";
            Header hashHeader = cookie.getResponse().getFirstHeader(HttpGatewayConstants.HEADER_HASH_ANS);
            if (hashHeader != null) {
                hash = hashHeader.getValue();
                int hashIndex = hash.indexOf(' ');
                if (hashIndex > 0) {
                    hashScheme = hash.substring(0, hashIndex).trim();
                    hashValue = hash.substring(hashIndex).trim();
                }
            }

            metadata = new FileMetadata(fileType, ingestTime, null, null, null, size, null, null, null, null,
                    null, version, dpl, hashScheme, hashValue, shred, retention, retentionHold, searchIndex,
                    replicated, null, null, customMetadata);

            if (symlinkTarget != null) {
                metadata.setSymlinkTarget(symlinkTarget);
            }
            getAdditionalMetadata(cookie.getResponse(), metadata, filePath);
        }

        if (metadata != null && symlinkTarget != null) {
            metadata.setSymlinkTarget(symlinkTarget);
        }

    } catch (IOException e) {
        handleIOExceptionFromRequest(e, "getting metadata", filePath);
    } finally {
        close();
    }

    return metadata;
}

From source file:com.linecorp.armeria.server.http.HttpServiceTest.java

@Test
public void testContentLength() throws Exception {
    // Test if the server responds with the 'content-length' header
    // even if it is the last response of the connection.
    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        HttpUriRequest req = new HttpGet(newUri("/200"));
        req.setHeader("Connection", "Close");
        try (CloseableHttpResponse res = hc.execute(req)) {
            assertThat(res.getStatusLine().toString(), is("HTTP/1.1 200 OK"));
            assertThat(res.containsHeader("Content-Length"), is(true));
            assertThat(res.getHeaders("Content-Length").length, is(1));
            assertThat(res.getHeaders("Content-Length")[0].getValue(), is("6"));
            assertThat(EntityUtils.toString(res.getEntity()), is("200 OK"));
        }/*from  w  w  w .j a va  2 s  .c  o m*/
    }

    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        // Ensure the HEAD response does not have content.
        try (CloseableHttpResponse res = hc.execute(new HttpHead(newUri("/200")))) {
            assertThat(res.getStatusLine().toString(), is("HTTP/1.1 200 OK"));
            assertThat(res.getEntity(), is(nullValue()));
        }

        // Ensure the 204 response does not have content.
        try (CloseableHttpResponse res = hc.execute(new HttpGet(newUri("/204")))) {
            assertThat(res.getStatusLine().toString(), is("HTTP/1.1 204 No Content"));
            assertThat(res.getEntity(), is(nullValue()));
        }
    }
}

From source file:com.googlecode.sardine.SardineImpl.java

public boolean exists(String url) throws SardineException {
    HttpHead head = new HttpHead(url);

    HttpResponse response = this.executeWrapper(head);

    StatusLine statusLine = response.getStatusLine();

    return SardineUtil.isGoodResponse(statusLine.getStatusCode());
}

From source file:org.nuxeo.ecm.core.opencmis.impl.CmisSuiteSession2.java

@Test
public void testContentStreamUsingHeadMethod() throws Exception {
    setUpData();//from  ww  w .ja v  a 2  s .  co m
    session.clear(); // clear cache

    doTestContentStream(new HttpHead(getURI("/testfolder1/testfile1")));
}