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.mariotaku.twidere.util.net.HttpClientImpl.java

@Override
public twitter4j.http.HttpResponse request(final twitter4j.http.HttpRequest req) throws TwitterException {
    try {//from  w  w w  .  jav a 2s  . c om
        HttpRequestBase commonsRequest;

        final HostAddressResolver resolver = conf.getHostAddressResolver();
        final String urlString = req.getURL();
        final URI urlOrig;
        try {
            urlOrig = new URI(urlString);
        } catch (final URISyntaxException e) {
            throw new TwitterException(e);
        }
        final String host = urlOrig.getHost(), authority = urlOrig.getAuthority();
        final String resolvedHost = resolver != null ? resolver.resolve(host) : null;
        final String resolvedUrl = !isEmpty(resolvedHost)
                ? urlString.replace("://" + host, "://" + resolvedHost)
                : urlString;

        final RequestMethod method = req.getMethod();
        if (method == RequestMethod.GET) {
            commonsRequest = new HttpGet(resolvedUrl);
        } else if (method == RequestMethod.POST) {
            final HttpPost post = new HttpPost(resolvedUrl);
            // parameter has a file?
            boolean hasFile = false;
            final HttpParameter[] params = req.getParameters();
            if (params != null) {
                for (final HttpParameter param : params) {
                    if (param.isFile()) {
                        hasFile = true;
                        break;
                    }
                }
                if (!hasFile) {
                    if (params.length > 0) {
                        post.setEntity(new UrlEncodedFormEntity(params));
                    }
                } else {
                    final MultipartEntity me = new MultipartEntity();
                    for (final HttpParameter param : params) {
                        if (param.isFile()) {
                            final ContentBody body;
                            if (param.getFile() != null) {
                                body = new FileBody(param.getFile(), param.getContentType());
                            } else {
                                body = new InputStreamBody(param.getFileBody(), param.getFileName(),
                                        param.getContentType());
                            }
                            me.addPart(param.getName(), body);
                        } else {
                            final ContentBody body = new StringBody(param.getValue(),
                                    "text/plain; charset=UTF-8", Charset.forName("UTF-8"));
                            me.addPart(param.getName(), body);
                        }
                    }
                    post.setEntity(me);
                }
            }
            post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
            commonsRequest = post;
        } else if (method == RequestMethod.DELETE) {
            commonsRequest = new HttpDelete(resolvedUrl);
        } else if (method == RequestMethod.HEAD) {
            commonsRequest = new HttpHead(resolvedUrl);
        } else if (method == RequestMethod.PUT) {
            commonsRequest = new HttpPut(resolvedUrl);
        } else
            throw new TwitterException("Unsupported request method " + method);
        final Map<String, String> headers = req.getRequestHeaders();
        for (final String headerName : headers.keySet()) {
            commonsRequest.addHeader(headerName, headers.get(headerName));
        }
        final Authorization authorization = req.getAuthorization();
        final String authorizationHeader = authorization != null ? authorization.getAuthorizationHeader(req)
                : null;
        if (authorizationHeader != null) {
            commonsRequest.addHeader("Authorization", authorizationHeader);
        }
        if (resolvedHost != null && !resolvedHost.isEmpty() && !resolvedHost.equals(host)) {
            commonsRequest.addHeader("Host", authority);
        }

        final ApacheHttpClientHttpResponseImpl res;
        try {
            res = new ApacheHttpClientHttpResponseImpl(client.execute(commonsRequest), conf);
        } catch (final IllegalStateException e) {
            throw new TwitterException("Please check your API settings.", e);
        } catch (final NullPointerException e) {
            // Bug http://code.google.com/p/android/issues/detail?id=5255
            throw new TwitterException("Please check your APN settings, make sure not to use WAP APNs.", e);
        } catch (final OutOfMemoryError e) {
            // I don't know why OOM thown, but it should be catched.
            System.gc();
            throw new TwitterException("Unknown error", e);
        }
        final int statusCode = res.getStatusCode();
        if (statusCode < OK || statusCode > ACCEPTED)
            throw new TwitterException(res.asString(), req, res);
        return res;
    } catch (final IOException e) {
        throw new TwitterException(e);
    }
}

From source file:edu.jhu.pha.vospace.storage.SwiftKeystoneStorageManager.java

public static FilesAccountInfo getAccountInfo()
        throws IOException, HttpException, FilesAuthorizationException, FilesException {

    HttpHead method = null;//  w  ww  .  ja  v a  2s  . c o  m

    try {
        method = new HttpHead(getFileUrl);
        method.getParams().setIntParameter("http.socket.timeout", connectionTimeOut);
        method.setHeader(FilesConstants.X_AUTH_TOKEN, strToken);
        FilesResponse response = new FilesResponse(client.execute(method));

        if (response.getStatusCode() == HttpStatus.SC_NO_CONTENT) {
            int nContainers = response.getAccountContainerCount();
            long totalSize = response.getAccountBytesUsed();
            return new FilesAccountInfo(totalSize, nContainers);
        } else {
            throw new FilesException("Unexpected return from server", response.getResponseHeaders(),
                    response.getStatusLine());
        }
    } finally {
        if (method != null)
            method.abort();
    }

}

From source file:jp.ambrosoli.quickrestclient.apache.service.ApacheHttpService.java

/**
 * {@link HttpUriRequest}?????? {@link HttpUriRequest}
 * ??????/*from   w w w . java2 s. c om*/
 * 
 * @param uri
 *            URI
 * @param method
 *            HTTP
 * @param params
 *            
 * @param encoding
 *            
 * @return {@link HttpRequestBase}
 */
protected HttpUriRequest createHttpUriRequest(final URI uri, final HttpMethod method,
        final RequestParams params, final String encoding) {
    switch (method) {
    case GET:
        return new HttpGet(this.addQueryString(uri, params, encoding));
    case POST:
        HttpPost httpPost = new HttpPost(uri);
        this.setFormEntity(httpPost, params, encoding);
        return httpPost;
    case PUT:
        HttpPut httpPut = new HttpPut(uri);
        this.setFormEntity(httpPut, params, encoding);
        return httpPut;
    case DELETE:
        return new HttpDelete(this.addQueryString(uri, params, encoding));
    case HEAD:
        return new HttpHead(this.addQueryString(uri, params, encoding));
    case OPTIONS:
        return new HttpOptions(this.addQueryString(uri, params, encoding));
    default:
        throw new AssertionError();
    }

}

From source file:io.crate.integrationtests.BlobHttpIntegrationTest.java

public List<String> getRedirectLocations(CloseableHttpClient client, String uri, InetSocketAddress address)
        throws IOException {
    CloseableHttpResponse response = null;
    try {/*w  w  w .ja  v  a  2 s. c  o m*/
        HttpClientContext context = HttpClientContext.create();
        HttpHead httpHead = new HttpHead(String.format(Locale.ENGLISH, "http://%s:%s/_blobs/%s",
                address.getHostName(), address.getPort(), uri));
        response = client.execute(httpHead, context);

        List<URI> redirectLocations = context.getRedirectLocations();
        if (redirectLocations == null) {
            // client might not follow redirects automatically
            if (response.containsHeader("location")) {
                List<String> redirects = new ArrayList<>(1);
                for (Header location : response.getHeaders("location")) {
                    redirects.add(location.getValue());
                }
                return redirects;
            }
            return Collections.emptyList();
        }

        List<String> redirects = new ArrayList<>(1);
        for (URI redirectLocation : redirectLocations) {
            redirects.add(redirectLocation.toString());
        }
        return redirects;
    } finally {
        if (response != null) {
            IOUtils.closeWhileHandlingException(response);
        }
    }
}

From source file:org.syncany.operations.init.ApplicationLink.java

private String resolveLink(String httpApplicationLink, int redirectCount)
        throws IllegalArgumentException, StorageException {
    if (redirectCount >= LINK_HTTP_MAX_REDIRECT_COUNT) {
        throw new IllegalArgumentException("Max. redirect count of " + LINK_HTTP_MAX_REDIRECT_COUNT
                + " for URL reached. Cannot find syncany:// link.");
    }//from   ww w  . ja  v  a 2 s .com

    try {
        logger.log(Level.INFO, "- Retrieving HTTP HEAD for " + httpApplicationLink + " ...");

        HttpHead headMethod = new HttpHead(httpApplicationLink);
        HttpResponse httpResponse = createHttpClient().execute(headMethod);

        // Find syncany:// link
        Header locationHeader = httpResponse.getLastHeader("Location");

        if (locationHeader == null) {
            throw new Exception("Link does not redirect to a syncany:// link.");
        }

        String locationHeaderUrl = locationHeader.getValue();
        Matcher locationHeaderMatcher = LINK_PATTERN.matcher(locationHeaderUrl);
        boolean isApplicationLink = locationHeaderMatcher.find();

        if (isApplicationLink) {
            String applicationLink = locationHeaderMatcher.group(0);
            logger.log(Level.INFO, "Resolved application link is: " + applicationLink);

            return applicationLink;
        } else {
            return resolveLink(locationHeaderUrl, ++redirectCount);
        }
    } catch (StorageException | IllegalArgumentException e) {
        throw e;
    } catch (Exception e) {
        throw new StorageException(e.getMessage(), e);
    }
}

From source file:riddimon.android.asianetautologin.HttpUtils.java

private HttpResponse execute(HttpMethod method, String url, Map<String, String> paramz,
        List<BasicHeader> headers) {
    if (!(method.equals(HttpMethod.GET) || method.equals(HttpMethod.DELETE) || method.equals(HttpMethod.PUT)
            || method.equals(HttpMethod.POST) || method.equals(HttpMethod.HEAD)) || TextUtils.isEmpty(url)) {
        logger.error("Invalid request : {} | {}", method.name(), url);
        return null;
    }/*from  www  . ja v  a 2  s. co  m*/
    logger.debug("HTTP {} : {}", method.name(), url);
    String query = paramz == null ? null : getEncodedParameters(paramz);
    logger.trace("Query String : {}", query);
    HttpResponse httpResponse = null;
    try {
        HttpUriRequest req = null;
        switch (method) {
        case GET:
        case HEAD:
        case DELETE:
            url = paramz != null && paramz.size() > 0 ? url + "?" + query : url;
            if (method.equals(HttpMethod.GET)) {
                req = new HttpGet(url);
            } else if (method.equals(HttpMethod.DELETE)) {
                req = new HttpDelete(url);
            } else if (method.equals(HttpMethod.HEAD)) {
                req = new HttpHead(url);
            }
            break;
        case POST:
        case PUT:
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            if (paramz != null) {
                for (Entry<String, String> entry : paramz.entrySet()) {
                    params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
            }
            UrlEncodedFormEntity entity = paramz == null ? null : new UrlEncodedFormEntity(params);
            //               HttpEntity entity = TextUtils.isEmpty(query) ? null
            //                     : new StringEntity(query);
            BasicHeader header = new BasicHeader(HTTP.CONTENT_ENCODING, "application/x-www-form-urlencoded");
            if (method.equals(HttpMethod.PUT)) {
                HttpPut putr = new HttpPut(url);
                if (entity != null) {
                    putr.setHeader(header);
                    putr.setEntity(entity);
                    req = putr;
                }
            } else if (method.equals(HttpMethod.POST)) {
                HttpPost postr = new HttpPost(url);
                if (entity != null) {
                    postr.setHeader(header);
                    if (headers != null) {
                        for (BasicHeader h : headers) {
                            postr.addHeader(h);
                        }
                    }
                    postr.setEntity(entity);
                    req = postr;
                }
            }
        }
        httpResponse = HttpManager.execute(req, debug, version);
    } catch (IOException e1) {
        e1.printStackTrace();
        logger.error("HTTP request failed : {}", e1);
    }
    return httpResponse;
}

From source file:com.sap.core.odata.fit.basic.BasicHttpTest.java

@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());
}

From source file:org.eclipse.aether.transport.http.HttpTransporter.java

@Override
protected void implPeek(PeekTask task) throws Exception {
    HttpHead request = commonHeaders(new HttpHead(resolve(task)));
    execute(request, null);/*  w  ww  . ja v  a 2s.c  o  m*/
}

From source file:org.fcrepo.apix.jena.impl.LdpContainerRegistry.java

private boolean exists(final URI uri) {
    try (CloseableHttpResponse response = client.execute(new HttpHead(uri))) {
        return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK;
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }//  ww w .ja  v a  2s  .  c o m
}