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

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

Introduction

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

Prototype

public HttpOptions(final String uri) 

Source Link

Usage

From source file:ca.uhn.fhir.rest.client.apache.ApacheHttpClient.java

private HttpRequestBase constructRequestBase(HttpEntity theEntity) {
    String url = myUrl.toString();
    switch (myRequestType) {
    case DELETE://from   ww w  .  jav  a2  s  . c  o m
        return new HttpDelete(url);
    case OPTIONS:
        return new HttpOptions(url);
    case POST:
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(theEntity);
        return httpPost;
    case PUT:
        HttpPut httpPut = new HttpPut(url);
        httpPut.setEntity(theEntity);
        return httpPut;
    case GET:
    default:
        return new HttpGet(url);
    }
}

From source file:com.meltmedia.cadmium.cli.DeployCommand.java

/**
 * Checks via an http options request that the endpoint exists to check for deployment state.
 * @param warName//from   w  ww .j  ava2s  . c o  m
 * @param url
 * @param client
 * @return
 */
public boolean canCheckWar(String warName, String url, HttpClient client) {
    HttpOptions opt = new HttpOptions(url + "/" + warName);
    try {
        HttpResponse response = client.execute(opt);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            Header allowHeader[] = response.getHeaders("Allow");
            for (Header allow : allowHeader) {
                List<String> values = Arrays.asList(allow.getValue().toUpperCase().split(","));
                if (values.contains("GET")) {
                    return true;
                }
            }
        }
        EntityUtils.consumeQuietly(response.getEntity());
    } catch (Exception e) {
        log.warn("Failed to check if endpoint exists.", e);
    } finally {
        opt.releaseConnection();
    }
    return false;
}

From source file:me.code4fun.roboq.Request.java

protected HttpUriRequest createHttpRequest(int method, String url, Options opts) {
    String url1 = makeUrl(url, opts);

    // Create HTTP request
    HttpUriRequest httpReq;/*from  w  w  w . j a v a2s.c o  m*/
    if (GET == method) {
        httpReq = new HttpGet(url1);
    } else if (POST == method) {
        httpReq = new HttpPost(url1);
    } else if (PUT == method) {
        httpReq = new HttpPut(url1);
    } else if (DELETE == method) {
        httpReq = new HttpDelete(url1);
    } else if (TRACE == method) {
        httpReq = new HttpTrace(url1);
    } else if (HEAD == method) {
        httpReq = new HttpHead(url1);
    } else if (OPTIONS == method) {
        httpReq = new HttpOptions(url1);
    } else {
        throw new IllegalStateException("Illegal HTTP method " + method);
    }

    // Set headers
    Map<String, Object> headers = opts.getHeaders();
    for (Map.Entry<String, Object> entry : headers.entrySet()) {
        String k = entry.getKey();
        Object v = entry.getValue();
        if (v != null && v.getClass().isArray()) {
            int len = Array.getLength(v);
            for (int i = 0; i < len; i++) {
                Object v0 = Array.get(v, i);
                httpReq.addHeader(k, o2s(v0, ""));
            }
        } else if (v instanceof List) {
            for (Object v0 : (List) v)
                httpReq.addHeader(k, o2s(v0, ""));
        } else {
            httpReq.addHeader(k, o2s(v, ""));
        }
    }

    // set body
    if (httpReq instanceof HttpEntityEnclosingRequestBase) {
        ((HttpEntityEnclosingRequestBase) httpReq).setEntity(createRequestBody(method, url, opts));
    }

    return httpReq;
}

From source file:net.ychron.unirestinst.http.HttpClientHelper.java

private HttpRequestBase prepareRequest(HttpRequest request, boolean async) {

    Object defaultHeaders = options.getOption(Option.DEFAULT_HEADERS);
    if (defaultHeaders != null) {
        @SuppressWarnings("unchecked")
        Set<Entry<String, String>> entrySet = ((Map<String, String>) defaultHeaders).entrySet();
        for (Entry<String, String> entry : entrySet) {
            request.header(entry.getKey(), entry.getValue());
        }//from w w  w  .j  a va  2 s  . co  m
    }

    if (!request.getHeaders().containsKey(USER_AGENT_HEADER)) {
        request.header(USER_AGENT_HEADER, USER_AGENT);
    }
    if (!request.getHeaders().containsKey(ACCEPT_ENCODING_HEADER)) {
        request.header(ACCEPT_ENCODING_HEADER, "gzip");
    }

    HttpRequestBase reqObj = null;

    String urlToRequest = null;
    try {
        URL url = new URL(request.getUrl());
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(),
                URLDecoder.decode(url.getPath(), "UTF-8"), "", url.getRef());
        urlToRequest = uri.toURL().toString();
        if (url.getQuery() != null && !url.getQuery().trim().equals("")) {
            if (!urlToRequest.substring(urlToRequest.length() - 1).equals("?")) {
                urlToRequest += "?";
            }
            urlToRequest += url.getQuery();
        } else if (urlToRequest.substring(urlToRequest.length() - 1).equals("?")) {
            urlToRequest = urlToRequest.substring(0, urlToRequest.length() - 1);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    switch (request.getHttpMethod()) {
    case GET:
        reqObj = new HttpGet(urlToRequest);
        break;
    case POST:
        reqObj = new HttpPost(urlToRequest);
        break;
    case PUT:
        reqObj = new HttpPut(urlToRequest);
        break;
    case DELETE:
        reqObj = new HttpDeleteWithBody(urlToRequest);
        break;
    case PATCH:
        reqObj = new HttpPatchWithBody(urlToRequest);
        break;
    case OPTIONS:
        reqObj = new HttpOptions(urlToRequest);
        break;
    case HEAD:
        reqObj = new HttpHead(urlToRequest);
        break;
    }

    Set<Entry<String, List<String>>> entrySet = request.getHeaders().entrySet();
    for (Entry<String, List<String>> entry : entrySet) {
        List<String> values = entry.getValue();
        if (values != null) {
            for (String value : values) {
                reqObj.addHeader(entry.getKey(), value);
            }
        }
    }

    // Set body
    if (!(request.getHttpMethod() == HttpMethod.GET || request.getHttpMethod() == HttpMethod.HEAD)) {
        if (request.getBody() != null) {
            HttpEntity entity = request.getBody().getEntity();
            if (async) {
                if (reqObj.getHeaders(CONTENT_TYPE) == null || reqObj.getHeaders(CONTENT_TYPE).length == 0) {
                    reqObj.setHeader(entity.getContentType());
                }
                try {
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    entity.writeTo(output);
                    NByteArrayEntity en = new NByteArrayEntity(output.toByteArray());
                    ((HttpEntityEnclosingRequestBase) reqObj).setEntity(en);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            } else {
                ((HttpEntityEnclosingRequestBase) reqObj).setEntity(entity);
            }
        }
    }

    return reqObj;
}

From source file:org.perfcake.message.sender.HttpClientSender.java

@Override
public void preSend(final Message message, final Properties messageAttributes) throws Exception {
    super.preSend(message, messageAttributes);

    if (storeCookies && localCookieManager.get() == null) {
        localCookieManager.set(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
    }/*from w w w. ja  v a 2 s.  c  om*/

    currentMethod = getDynamicMethod(messageAttributes);

    payloadLength = 0;
    if (message == null) {
        payload = null;
    } else if (message.getPayload() != null) {
        payload = message.getPayload().toString();
        payloadLength = payload.length();
    }

    final URI uri = url.toURI();
    switch (currentMethod) {
    case GET:
        currentRequest = new HttpGet(uri);
        break;
    case POST:
        currentRequest = new HttpPost(uri);
        break;
    case PUT:
        currentRequest = new HttpPut(uri);
        break;
    case PATCH:
        currentRequest = new HttpPatch(uri);
        break;
    case DELETE:
        currentRequest = new HttpDelete(uri);
        break;
    case HEAD:
        currentRequest = new HttpHead(uri);
        break;
    case TRACE:
        currentRequest = new HttpTrace(uri);
        break;
    case OPTIONS:
        currentRequest = new HttpOptions(uri);
    }

    StringEntity msg = null;
    if (payload != null && (currentRequest instanceof HttpEntityEnclosingRequestBase)) {
        ((HttpEntityEnclosingRequestBase) currentRequest).setEntity(
                new StringEntity(payload, ContentType.create("text/plain", Utils.getDefaultEncoding())));
    }

    if (storeCookies) {
        popCookies();
    }

    if (log.isDebugEnabled()) {
        log.debug("Setting HTTP headers: ");
    }

    // set message properties as HTTP headers
    if (message != null) {
        for (final Entry<Object, Object> property : message.getProperties().entrySet()) {
            final String pKey = property.getKey().toString();
            final String pValue = property.getValue().toString();
            currentRequest.setHeader(pKey, pValue);
            if (log.isDebugEnabled()) {
                log.debug(pKey + ": " + pValue);
            }
        }
    }

    // set message headers as HTTP headers
    if (message != null) {
        if (message.getHeaders().size() > 0) {
            for (final Entry<Object, Object> property : message.getHeaders().entrySet()) {
                final String pKey = property.getKey().toString();
                final String pValue = property.getValue().toString();
                currentRequest.setHeader(pKey, pValue);
                if (log.isDebugEnabled()) {
                    log.debug(pKey + ": " + pValue);
                }
            }
        }
    }

    if (log.isDebugEnabled()) {
        log.debug("End of HTTP headers.");
    }
}

From source file:com.sun.jersey.client.apache4.ApacheHttpClient4Handler.java

private HttpUriRequest getUriHttpRequest(final ClientRequest cr) {
    final String strMethod = cr.getMethod();
    final URI uri = cr.getURI();

    final Boolean bufferingEnabled = isBufferingEnabled(cr);
    final HttpEntity entity = getHttpEntity(cr, bufferingEnabled);
    final HttpUriRequest request;

    if (strMethod.equals("GET")) {
        request = new HttpGet(uri);
    } else if (strMethod.equals("POST")) {
        request = new HttpPost(uri);
    } else if (strMethod.equals("PUT")) {
        request = new HttpPut(uri);
    } else if (strMethod.equals("DELETE")) {
        request = new HttpDelete(uri);
    } else if (strMethod.equals("HEAD")) {
        request = new HttpHead(uri);
    } else if (strMethod.equals("OPTIONS")) {
        request = new HttpOptions(uri);
    } else {/*ww w . j  a  v  a 2  s  .  c o m*/
        request = new HttpEntityEnclosingRequestBase() {
            @Override
            public String getMethod() {
                return strMethod;
            }

            @Override
            public URI getURI() {
                return uri;
            }
        };
    }

    if (entity != null && request instanceof HttpEntityEnclosingRequestBase) {
        ((HttpEntityEnclosingRequestBase) request).setEntity(entity);
    } else if (entity != null) {
        throw new ClientHandlerException(
                "Adding entity to http method " + cr.getMethod() + " is not supported.");
    }

    // Set the read timeout
    final Integer readTimeout = (Integer) cr.getProperties().get(ApacheHttpClient4Config.PROPERTY_READ_TIMEOUT);
    if (readTimeout != null) {
        request.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, readTimeout);
    }

    // Set chunk size
    final Integer chunkSize = (Integer) cr.getProperties().get(ClientConfig.PROPERTY_CHUNKED_ENCODING_SIZE);
    if (chunkSize != null && !bufferingEnabled) {
        client.getParams().setIntParameter(CoreConnectionPNames.MIN_CHUNK_LIMIT, chunkSize);
    }

    return request;
}

From source file:org.apache.cxf.systest.jaxrs.cors.CrossOriginSimpleTest.java

@Test
public void preflightPostClassAnnotationPass() throws ClientProtocolException, IOException {
    HttpClient httpclient = HttpClientBuilder.create().build();
    HttpOptions httpoptions = new HttpOptions("http://localhost:" + PORT + "/antest/unannotatedPost");
    httpoptions.addHeader("Origin", "http://area51.mil:31415");
    httpoptions.addHeader("Content-Type", "application/json");
    httpoptions.addHeader(CorsHeaderConstants.HEADER_AC_REQUEST_METHOD, "POST");
    httpoptions.addHeader(CorsHeaderConstants.HEADER_AC_REQUEST_HEADERS, "X-custom-1");
    HttpResponse response = httpclient.execute(httpoptions);
    assertEquals(200, response.getStatusLine().getStatusCode());
    Header[] origin = response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_ORIGIN);
    assertEquals(1, origin.length);/*w  ww  .j  av  a 2s.c o  m*/
    assertEquals("http://area51.mil:31415", origin[0].getValue());
    Header[] method = response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_METHODS);
    assertEquals(1, method.length);
    assertEquals("POST", method[0].getValue());
    Header[] requestHeaders = response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_HEADERS);
    assertEquals(1, requestHeaders.length);
    assertEquals("X-custom-1", requestHeaders[0].getValue());
    if (httpclient instanceof Closeable) {
        ((Closeable) httpclient).close();
    }

}

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

/**
 * {@link HttpUriRequest}?????? {@link HttpUriRequest}
 * ??????/*  www  . j ava  2s.c o  m*/
 * 
 * @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:com.reachcall.pretty.http.ProxyServlet.java

@Override
public void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Match match = (Match) req.getAttribute("match");
    HttpOptions method = new HttpOptions(match.toURL());
    copyHeaders(req, method);/*  w  w w.  j  av a2  s  .  c om*/
    this.execute(match, method, req, resp);
}

From source file:com.falcon.orca.actors.Generator.java

private HttpUriRequest prepareRequest() throws URISyntaxException, JsonProcessingException {
    HttpUriRequest request;// w  ww . j av a 2  s .  c  o m
    switch (method) {
    case POST: {
        String postUrl = isUrlDynamic ? dataStore.fillURLWithData() : url;
        AbstractHttpEntity postData;
        try {
            postData = isBodyDynamic
                    ? new StringEntity(dataStore.fillTemplateWithData(), StandardCharsets.UTF_8)
                    : new ByteArrayEntity(staticRequestData == null ? new byte[0] : staticRequestData);
        } catch (IllegalArgumentException ile) {
            postData = new ByteArrayEntity(new byte[0]);
            log.error("Post body is null, sending blank.");
        }
        request = new HttpPost(postUrl);
        ((HttpPost) request).setEntity(postData);
        break;
    }
    case GET: {
        String getUrl = isUrlDynamic ? dataStore.fillURLWithData() : url;
        request = new HttpGet(getUrl);
        break;
    }
    case PUT: {
        String putUrl = isUrlDynamic ? dataStore.fillURLWithData() : url;
        AbstractHttpEntity putData;
        try {
            putData = isBodyDynamic ? new StringEntity(dataStore.fillTemplateWithData(), StandardCharsets.UTF_8)
                    : new ByteArrayEntity(staticRequestData == null ? new byte[0] : staticRequestData);
        } catch (IllegalArgumentException ile) {
            putData = new ByteArrayEntity(new byte[0]);
            log.error("Post body is null, sending blank.");
        }
        request = new HttpPut(putUrl);
        ((HttpPut) request).setEntity(putData);
        break;
    }
    case DELETE: {
        String deleteUrl = isUrlDynamic ? dataStore.fillURLWithData() : url;
        request = new HttpDelete(deleteUrl);
        break;
    }
    case OPTIONS: {
        String optionsUrl = isUrlDynamic ? dataStore.fillURLWithData() : url;
        request = new HttpOptions(optionsUrl);
        break;
    }
    case HEAD: {
        String headUrl = isUrlDynamic ? dataStore.fillURLWithData() : url;
        request = new HttpHead(headUrl);
        break;
    }
    default:
        throw new URISyntaxException(url + ":" + method,
                "Wrong method supplied, available methods are POST, " + "GET, PUT, DELETE, HEAD, OPTIONS");
    }
    if (headers != null) {
        headers.forEach(request::addHeader);
    }
    return request;
}