Example usage for org.apache.http.client.methods HttpPost METHOD_NAME

List of usage examples for org.apache.http.client.methods HttpPost METHOD_NAME

Introduction

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

Prototype

String METHOD_NAME

To view the source code for org.apache.http.client.methods HttpPost METHOD_NAME.

Click Source Link

Usage

From source file:com.linkedin.pinot.common.utils.FileUploadDownloadClient.java

private static HttpUriRequest getUploadSegmentRequest(URI uri, String segmentName, File segmentFile,
        @Nullable List<Header> headers, @Nullable List<NameValuePair> parameters, int socketTimeoutMs) {
    return getUploadFileRequest(HttpPost.METHOD_NAME, uri, getContentBody(segmentName, segmentFile), headers,
            parameters, socketTimeoutMs);
}

From source file:org.jasig.portlet.emailpreview.dao.exchange.AutodiscoverRedirectStrategy.java

/**
 * Overrides behavior to follow redirects for POST messages, AND to have the redirect be a POST.  Behavior of
 * <code>DefaultRedirectStrategy</code> is to use a GET for the redirect (though against spec this is the
 * de-facto standard, see http://www.mail-archive.com/httpclient-users@hc.apache.org/msg06327.html and
 * http://www.alanflavell.org.uk/www/post-redirect.html).
 *
 * For our application, we want to follow the redirect for a 302 as long as it is to a safe location and
 * have the redirect be a POST.//from w w  w.  jav a2 s  .c  o m
 *
 * This code is modified from http-components' http-client 4.2.5.  Since we only use POST the code for the
 * other HTTP methods has been removed to simplify this method.
 *
 * @param request Http request
 * @param response Http response
 * @param context Http context
 * @return Request to issue to the redirected location
 * @throws ProtocolException protocol exception
 */
@Override
public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response,
        final HttpContext context) throws ProtocolException {
    URI uri = getLocationURI(request, response, context);
    log.info("Following redirect to {}", uri.toString());
    String method = request.getRequestLine().getMethod();
    int status = response.getStatusLine().getStatusCode();

    // Insure location is safe
    if (matchesPatternSet(uri, unsafeUriPatterns)) {
        log.warn("Not following to URI {} - matches a configured unsafe URI pattern", uri.toString());
        throw new EmailPreviewException("Autodiscover redirected to unsafe URI " + uri.toString());
    }

    if (!matchesPatternSet(uri, uriRequirementPatterns) && uriRequirementPatterns.size() > 0) {
        log.warn("Not following to URI {} - URI does not match a required URI pattern", uri.toString());
        throw new EmailPreviewException(
                "Autodiscover redirected to URI not matching required pattern. URI=" + uri.toString());
    }

    // Follow forwards for 301 and 302 in addition to 307, to validate the redirect location,
    // and to use a POST method.
    if (status == HttpStatus.SC_TEMPORARY_REDIRECT || status == HttpStatus.SC_MOVED_PERMANENTLY
            || status == HttpStatus.SC_MOVED_TEMPORARILY) {
        if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
            return copyEntity(new HttpPost(uri), request);
        }
    }

    // Should not get here, but return sensible value just in case.  A GET will likely fail.
    return new HttpGet(uri);
}

From source file:com.linkedin.pinot.common.utils.FileUploadDownloadClient.java

private static HttpUriRequest getUploadSegmentRequest(URI uri, String segmentName, InputStream inputStream,
        @Nullable List<Header> headers, @Nullable List<NameValuePair> parameters, int socketTimeoutMs) {
    return getUploadFileRequest(HttpPost.METHOD_NAME, uri, getContentBody(segmentName, inputStream), headers,
            parameters, socketTimeoutMs);
}

From source file:org.jasig.portlet.calendar.adapter.exchange.AutodiscoverRedirectStrategy.java

/**
 * Overrides behavior to follow redirects for POST messages, AND to have the redirect be a POST.  Behavior of
 * <code>DefaultRedirectStrategy</code> is to use a GET for the redirect (though against spec this is the
 * de-facto standard, see http://www.mail-archive.com/httpclient-users@hc.apache.org/msg06327.html and
 * http://www.alanflavell.org.uk/www/post-redirect.html).
 *
 * For our application, we want to follow the redirect for a 302 as long as it is to a safe location and
 * have the redirect be a POST.//from www .ja v a 2 s .  com
 *
 * This code is modified from http-components' http-client 4.2.5.  Since we only use POST the code for the
 * other HTTP methods has been removed to simplify this method.
 *
 * @param request Http request
 * @param response Http response
 * @param context Http context
 * @return Request to issue to the redirected location
 * @throws ProtocolException protocol exception
 */
@Override
public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response,
        final HttpContext context) throws ProtocolException {
    URI uri = getLocationURI(request, response, context);
    log.info("Following redirect to {}", uri.toString());
    String method = request.getRequestLine().getMethod();
    int status = response.getStatusLine().getStatusCode();

    // Insure location is safe
    if (matchesPatternSet(uri, unsafeUriPatterns)) {
        log.warn("Not following to URI {} - matches a configured unsafe URI pattern", uri.toString());
        throw new CalendarException("Autodiscover redirected to unsafe URI " + uri.toString());
    }

    if (!matchesPatternSet(uri, uriRequirementPatterns) && uriRequirementPatterns.size() > 0) {
        log.warn("Not following to URI {} - URI does not match a required URI pattern", uri.toString());
        throw new CalendarException(
                "Autodiscover redirected to URI not matching required pattern. URI=" + uri.toString());
    }

    // Follow forwards for 301 and 302 in addition to 307, to validate the redirect location,
    // and to use a POST method.
    if (status == HttpStatus.SC_TEMPORARY_REDIRECT || status == HttpStatus.SC_MOVED_PERMANENTLY
            || status == HttpStatus.SC_MOVED_TEMPORARILY) {
        if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
            return copyEntity(new HttpPost(uri), request);
        }
    }

    // Should not get here, but return sensible value just in case.  A GET will likely fail.
    return new HttpGet(uri);
}

From source file:com.microsoft.exchange.autodiscover.AutodiscoverRedirectStrategy.java

/**
* Overrides behavior to follow redirects for POST messages, AND to have the redirect be a POST.  Behavior of
* <code>DefaultRedirectStrategy</code> is to use a GET for the redirect (though against spec this is the
* de-facto standard, see http://www.mail-archive.com/httpclient-users@hc.apache.org/msg06327.html and
* http://www.alanflavell.org.uk/www/post-redirect.html).
*
* For our application, we want to follow the redirect for a 302 as long as it is to a safe location and
* have the redirect be a POST./*  www . j  a  v  a2 s.  co m*/
*
* This code is modified from http-components' http-client 4.2.5.  Since we only use POST the code for the
* other HTTP methods has been removed to simplify this method.
*
* @param request Http request
* @param response Http response
* @param context Http context
* @return Request to issue to the redirected location
* @throws ProtocolException protocol exception
*/
@Override
public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response,
        final HttpContext context) throws ProtocolException {
    URI uri = getLocationURI(request, response, context);
    log.info("Following redirect to " + uri.toString());
    String method = request.getRequestLine().getMethod();
    int status = response.getStatusLine().getStatusCode();

    // Insure location is safe
    if (matchesPatternSet(uri, unsafeUriPatterns)) {
        log.warn("Not following to URI {} - matches a configured unsafe URI pattern " + uri.toString());
        throw new ExchangeWebServicesRuntimeException(
                "Autodiscover redirected to unsafe URI " + uri.toString());
    }

    if (!matchesPatternSet(uri, uriRequirementPatterns) && uriRequirementPatterns.size() > 0) {
        log.warn("Not following to URI {} - URI does not match a required URI pattern " + uri.toString());
        throw new ExchangeWebServicesRuntimeException(
                "Autodiscover redirected to URI not matching required pattern. URI=" + uri.toString());
    }

    // Follow forwards for 301 and 302 in addition to 307, to validate the redirect location,
    // and to use a POST method.
    if (status == HttpStatus.SC_TEMPORARY_REDIRECT || status == HttpStatus.SC_MOVED_PERMANENTLY
            || status == HttpStatus.SC_MOVED_TEMPORARILY) {
        if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
            return copyEntity(new HttpPost(uri), request);
        }
    }

    // Should not get here, but return sensible value just in case.  A GET will likely fail.
    return new HttpGet(uri);
}

From source file:com.mywork.framework.util.RemoteHttpUtil.java

/**
 * ?getpost????//from w w w .  j a va 2s. c  o m
 */
public static String fetchSimpleHttpResponse(String method, String contentUrl, Map<String, String> headerMap,
        Map<String, String> bodyMap) throws IOException {
    Executor executor = Executor.newInstance(httpClient);
    if (HttpGet.METHOD_NAME.equalsIgnoreCase(method)) {
        String result = contentUrl;
        StringBuilder sb = new StringBuilder();
        sb.append(contentUrl);
        if (bodyMap != null && !bodyMap.isEmpty()) {
            if (contentUrl.indexOf("?") > 0) {
                sb.append("&");
            } else {
                sb.append("?");
            }
            result = Joiner.on("&").appendTo(sb, bodyMap.entrySet()).toString();
        }

        return executor.execute(Request.Get(result)).returnContent().asString();
    }
    if (HttpPost.METHOD_NAME.equalsIgnoreCase(method)) {
        Request request = Request.Post(contentUrl);
        if (headerMap != null && !headerMap.isEmpty()) {
            for (Map.Entry<String, String> m : headerMap.entrySet()) {
                request.addHeader(m.getKey(), m.getValue());
            }
        }
        if (bodyMap != null && !bodyMap.isEmpty()) {
            Form form = Form.form();
            for (Map.Entry<String, String> m : bodyMap.entrySet()) {
                form.add(m.getKey(), m.getValue());
            }
            request.bodyForm(form.build());
        }
        return executor.execute(request).returnContent().asString();
    }
    return null;

}

From source file:com.microsoft.windowsazure.mobileservices.http.MobileServiceHttpClient.java

/**
 * Makes a request over HTTP/* w w  w .j av a  2 s  .  c  o m*/
 *
 * @param path           The path of the request URI
 * @param content        The byte array to send as the request body
 * @param httpMethod     The HTTP Method used to invoke the API
 * @param requestHeaders The extra headers to send in the request
 * @param parameters     The query string parameters sent in the request
 * @param features       The features used in the request
 */
public ListenableFuture<ServiceFilterResponse> request(String path, byte[] content, String httpMethod,
        List<Pair<String, String>> requestHeaders, List<Pair<String, String>> parameters,
        EnumSet<MobileServiceFeatures> features) {
    final SettableFuture<ServiceFilterResponse> future = SettableFuture.create();

    if (path == null || path.trim().equals("")) {
        future.setException(new IllegalArgumentException("request path cannot be null"));
        return future;
    }

    if (httpMethod == null || httpMethod.trim().equals("")) {
        future.setException(new IllegalArgumentException("httpMethod cannot be null"));
        return future;
    }

    Uri.Builder uriBuilder = Uri.parse(mClient.getAppUrl().toString()).buildUpon();
    uriBuilder.path(path);

    if (parameters != null && parameters.size() > 0) {
        for (Pair<String, String> parameter : parameters) {
            uriBuilder.appendQueryParameter(parameter.first, parameter.second);
        }
    }

    ServiceFilterRequestImpl request;
    String url = uriBuilder.build().toString();

    if (httpMethod.equalsIgnoreCase(HttpGet.METHOD_NAME)) {
        request = new ServiceFilterRequestImpl(new HttpGet(url), mClient.getAndroidHttpClientFactory());
    } else if (httpMethod.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
        request = new ServiceFilterRequestImpl(new HttpPost(url), mClient.getAndroidHttpClientFactory());
    } else if (httpMethod.equalsIgnoreCase(HttpPut.METHOD_NAME)) {
        request = new ServiceFilterRequestImpl(new HttpPut(url), mClient.getAndroidHttpClientFactory());
    } else if (httpMethod.equalsIgnoreCase(HttpPatch.METHOD_NAME)) {
        request = new ServiceFilterRequestImpl(new HttpPatch(url), mClient.getAndroidHttpClientFactory());
    } else if (httpMethod.equalsIgnoreCase(HttpDelete.METHOD_NAME)) {
        request = new ServiceFilterRequestImpl(new HttpDelete(url), mClient.getAndroidHttpClientFactory());
    } else {
        future.setException(new IllegalArgumentException("httpMethod not supported"));
        return future;
    }

    String featuresHeader = MobileServiceFeatures.featuresToString(features);
    if (featuresHeader != null) {
        if (requestHeaders == null) {
            requestHeaders = new ArrayList<Pair<String, String>>();
        }

        boolean containsFeatures = false;
        for (Pair<String, String> header : requestHeaders) {
            if (header.first.equals(X_ZUMO_FEATURES)) {
                containsFeatures = true;
                break;
            }
        }

        if (!containsFeatures) {
            // Clone header list to prevent changing user's list
            requestHeaders = new ArrayList<Pair<String, String>>(requestHeaders);
            requestHeaders.add(new Pair<String, String>(X_ZUMO_FEATURES, featuresHeader));
        }
    }

    if (requestHeaders != null && requestHeaders.size() > 0) {
        for (Pair<String, String> header : requestHeaders) {
            request.addHeader(header.first, header.second);
        }
    }

    if (content != null) {
        try {
            request.setContent(content);
        } catch (Exception e) {
            future.setException(e);
            return future;
        }
    }

    MobileServiceConnection conn = mClient.createConnection();

    new RequestAsyncTask(request, conn) {
        @Override
        protected void onPostExecute(ServiceFilterResponse response) {
            if (mTaskException != null) {
                future.setException(mTaskException);
            } else {
                future.set(response);
            }
        }
    }.executeTask();

    return future;
}

From source file:org.apache.edgent.connectors.http.HttpStreams.java

/**
 * Make an HTTP POST request with JsonObject. <br>
 * /*from ww  w . j  av a 2 s . c o  m*/
 * Method specifically works with JsonObjects. For each JsonObject in the stream, 
 * HTTP POST request is executed on provided uri. Request body is filled using
 * HttpEntity provided by body function. As a result, Response is added to
 * the response TStream.<br>
 * 
 * Sample usage:<br>
 * 
 * <pre>
 * {@code
 *     DirectProvider ep = new DirectProvider();
 *     Topology topology = ep.newTopology();
 *     final String url = "http://httpbin.org/post";
 * 
 *     JsonObject body = new JsonObject();
 *     body.addProperty("foo", "abc");
 *     body.addProperty("bar", 42);
 * 
 *     TStream<JsonObject> stream = topology.collection(Arrays.asList(body));
 *     TStream<JsonObject> rc = HttpStreams.postJson(stream,
 *             HttpClients::noAuthentication, t -> url, t -> t);
 * }
 * </pre>
 * 
 * <br>
 * See HttpTest for example. <br>
 * 
 * @param stream - JsonObject TStream.
 * @param clientCreator - CloseableHttpClient supplier preferably created using {@link HttpClients}
 * @param uri - URI function which returns URI string
 * @param body - Function that returns JsonObject which will be set as a body for the request.
 * @return TStream of JsonObject which contains responses of POST requests
 * 
 * @see HttpStreams#requestsWithBody(TStream, Supplier, Function, Function, Function, BiFunction)
 */
public static TStream<JsonObject> postJson(TStream<JsonObject> stream,
        Supplier<CloseableHttpClient> clientCreator, Function<JsonObject, String> uri,
        UnaryOperator<JsonObject> body) {

    return HttpStreams.<JsonObject, JsonObject>requestsWithBody(stream, clientCreator,
            t -> HttpPost.METHOD_NAME, uri, t -> new ByteArrayEntity(body.apply(t).toString().getBytes()),
            HttpResponders.json());
}

From source file:code.google.restclient.core.Hitter.java

/**
 * Method to make POST or PUT request by sending http entity (as body)
 *//*from   w ww.  j  a v  a 2s.c o m*/
public void hit(String url, String methodName, HttpHandler handler, Map<String, String> requestHeaders)
        throws Exception {

    if (DEBUG_ENABLED)
        LOG.debug("hit() - method => " + methodName + ", url => " + url);

    if (HttpGet.METHOD_NAME.equals(methodName)) {
        if (DEBUG_ENABLED)
            LOG.debug("hit() - ===> GET " + url);
        hit(url, new HttpGet(url), handler, requestHeaders);
    } else if (HttpHead.METHOD_NAME.equals(methodName)) {
        if (DEBUG_ENABLED)
            LOG.debug("hit() - ===> HEAD " + url);
        hit(url, new HttpHead(url), handler, requestHeaders);
    } else if (HttpDelete.METHOD_NAME.equals(methodName)) {
        if (DEBUG_ENABLED)
            LOG.debug("hit() - ===> DELETE " + url);
        hit(url, new HttpDelete(url), handler, requestHeaders);
    } else if (HttpOptions.METHOD_NAME.equals(methodName)) {
        if (DEBUG_ENABLED)
            LOG.debug("hit() - ===> OPTIONS " + url);
        hit(url, new HttpOptions(url), handler, requestHeaders);
    } else if (HttpTrace.METHOD_NAME.equals(methodName)) {
        if (DEBUG_ENABLED)
            LOG.debug("hit() - ===> TRACE " + url);
        hit(url, new HttpTrace(url), handler, requestHeaders);
    } else if (HttpPost.METHOD_NAME.equals(methodName)) { // POST
        if (DEBUG_ENABLED)
            LOG.debug("hit() - ===> POST " + url);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(handler.getReqBodyEntity());
        hit(url, httpPost, handler, requestHeaders);
    } else if (HttpPut.METHOD_NAME.equals(methodName)) { // PUT
        if (DEBUG_ENABLED)
            LOG.debug("hit() - ===> PUT " + url);
        HttpPut httpPut = new HttpPut(url);
        httpPut.setEntity(handler.getReqBodyEntity());
        hit(url, httpPut, handler, requestHeaders);
    } else {
        throw new IllegalArgumentException("hit(): Unsupported method => " + methodName);
    }
}

From source file:com.pushinginertia.commons.net.client.AbstractHttpPostClient.java

/**
 * Creates an http connection to the remote host so that a POST request can be made. This only creates the
 * connection instance and configures it, but does not actually open the remote connection.
 *
 * @param contentLength number of bytes in the payload to send
 * @return never null/*  w  ww. ja  v a 2  s  . c o m*/
 * @throws HttpConnectException if a problem occurs trying to instantiate the connection object
 */
protected C configureConnection(final int contentLength) throws HttpConnectException {
    try {
        final URL u = new URL(getUrl());
        @SuppressWarnings("unchecked")
        final C con = (C) u.openConnection();
        con.setDoOutput(true); // indicates a POST request
        con.setRequestMethod(HttpPost.METHOD_NAME);
        con.setFixedLengthStreamingMode(contentLength); // content length is known so set it for efficiency
        con.setConnectTimeout(getConnectionTimeout()); // default value is zero (never time out)
        con.setRequestProperty("Accept", "application/xml");
        con.setRequestProperty("Content-Type", "application/xml");
        con.setRequestProperty("User-Agent", userAgent);
        return con;
    } catch (Exception e) {
        final String msg = "Cannot open connection to [" + getUrl() + "]: " + e.getMessage();
        LOG.error(getClass().getSimpleName(), msg, e);
        throw new HttpConnectException(msg, e);
    }
}