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.jaspersoft.ireport.jasperserver.ws.http.JSSCommonsHTTPSender.java

/**
 * invoke creates a socket connection, sends the request SOAP message and
 * then reads the response SOAP message back from the SOAP server
 *
 * @param msgContext//from w  w  w . ja v a  2  s  . co  m
 *            the messsage context
 *
 * @throws AxisFault
 */
public void invoke(final MessageContext msgContext) throws AxisFault {
    if (log.isDebugEnabled())
        log.debug(Messages.getMessage("enter00", "CommonsHTTPSender::invoke"));
    Request req = null;
    Response response = null;
    try {
        if (exec == null) {
            targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL));
            String userID = msgContext.getUsername();
            String passwd = msgContext.getPassword();
            // if UserID is not part of the context, but is in the URL, use
            // the one in the URL.
            if ((userID == null) && (targetURL.getUserInfo() != null)) {
                String info = targetURL.getUserInfo();
                int sep = info.indexOf(':');

                if ((sep >= 0) && (sep + 1 < info.length())) {
                    userID = info.substring(0, sep);
                    passwd = info.substring(sep + 1);
                } else
                    userID = info;
            }
            Credentials cred = new UsernamePasswordCredentials(userID, passwd);
            if (userID != null) {
                // if the username is in the form "user\domain"
                // then use NTCredentials instead.
                int domainIndex = userID.indexOf("\\");
                if (domainIndex > 0) {
                    String domain = userID.substring(0, domainIndex);
                    if (userID.length() > domainIndex + 1) {
                        String user = userID.substring(domainIndex + 1);
                        cred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain);
                    }
                }
            }
            HttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy() {

                public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response,
                        final HttpContext context) throws ProtocolException {
                    URI uri = getLocationURI(request, response, context);
                    String method = request.getRequestLine().getMethod();
                    if (method.equalsIgnoreCase(HttpHead.METHOD_NAME))
                        return new HttpHead(uri);
                    else if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
                        HttpPost httpPost = new HttpPost(uri);
                        httpPost.addHeader(request.getFirstHeader("Authorization"));
                        httpPost.addHeader(request.getFirstHeader("SOAPAction"));
                        httpPost.addHeader(request.getFirstHeader("Content-Type"));
                        httpPost.addHeader(request.getFirstHeader("User-Agent"));
                        httpPost.addHeader(request.getFirstHeader("SOAPAction"));
                        if (request instanceof HttpEntityEnclosingRequest)
                            httpPost.setEntity(((HttpEntityEnclosingRequest) request).getEntity());
                        return httpPost;
                    } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) {
                        return new HttpGet(uri);
                    } else {
                        throw new IllegalStateException(
                                "Redirect called on un-redirectable http method: " + method);
                    }
                }
            }).build();

            exec = Executor.newInstance(httpClient);
            HttpHost host = new HttpHost(targetURL.getHost(), targetURL.getPort(), targetURL.getProtocol());
            exec.auth(host, cred);
            exec.authPreemptive(host);
            HttpUtils.setupProxy(exec, targetURL.toURI());
        }
        boolean posting = true;

        // If we're SOAP 1.2, allow the web method to be set from the
        // MessageContext.
        if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
            String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD);
            if (webMethod != null)
                posting = webMethod.equals(HTTPConstants.HEADER_POST);
        }
        HttpHost proxy = HttpUtils.getUnauthProxy(exec, targetURL.toURI());
        if (posting) {
            req = Request.Post(targetURL.toString());
            if (proxy != null)
                req.viaProxy(proxy);
            Message reqMessage = msgContext.getRequestMessage();

            addContextInfo(req, msgContext, targetURL);
            Iterator<?> it = reqMessage.getAttachments();
            if (it.hasNext()) {
                ByteArrayOutputStream bos = null;
                try {
                    bos = new ByteArrayOutputStream();
                    reqMessage.writeTo(bos);
                    req.body(new ByteArrayEntity(bos.toByteArray()));
                } finally {
                    FileUtils.closeStream(bos);
                }
            } else
                req.body(new StringEntity(reqMessage.getSOAPPartAsString()));

        } else {
            req = Request.Get(targetURL.toString());
            if (proxy != null)
                req.viaProxy(proxy);
            addContextInfo(req, msgContext, targetURL);
        }

        response = exec.execute(req);
        response.handleResponse(new ResponseHandler<String>() {

            public String handleResponse(final HttpResponse response) throws IOException {
                HttpEntity en = response.getEntity();
                InputStream in = null;
                try {
                    StatusLine statusLine = response.getStatusLine();
                    int returnCode = statusLine.getStatusCode();
                    String contentType = en.getContentType().getValue();

                    in = new BufferedHttpEntity(en).getContent();
                    // String str = IOUtils.toString(in);
                    if (returnCode > 199 && returnCode < 300) {
                        // SOAP return is OK - so fall through
                    } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
                        // For now, if we're SOAP 1.2, fall
                        // through, since the range of
                        // valid result codes is much greater
                    } else if (contentType != null && !contentType.equals("text/html")
                            && ((returnCode > 499) && (returnCode < 600))) {
                        // SOAP Fault should be in here - so
                        // fall through
                    } else {
                        String statusMessage = statusLine.getReasonPhrase();
                        AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null,
                                null);
                        fault.setFaultDetailString(
                                Messages.getMessage("return01", "" + returnCode, IOUtils.toString(in)));
                        fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE,
                                Integer.toString(returnCode));
                        throw fault;
                    }
                    Header contentEncoding = response.getFirstHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
                    if (contentEncoding != null) {
                        if (contentEncoding.getValue().equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP))
                            in = new GZIPInputStream(in);
                        else {
                            AxisFault fault = new AxisFault("HTTP", "unsupported content-encoding of '"
                                    + contentEncoding.getValue() + "' found", null, null);
                            throw fault;
                        }

                    }

                    // Transfer HTTP headers of HTTP message
                    // to MIME headers of SOAP
                    // message
                    MimeHeaders mh = new MimeHeaders();
                    for (Header h : response.getAllHeaders())
                        mh.addHeader(h.getName(), h.getValue());
                    Message outMsg = new Message(in, false, mh);

                    outMsg.setMessageType(Message.RESPONSE);
                    msgContext.setResponseMessage(outMsg);
                    if (log.isDebugEnabled()) {
                        log.debug("\n" + Messages.getMessage("xmlRecd00"));
                        log.debug("-----------------------------------------------");
                        log.debug(outMsg.getSOAPPartAsString());
                    }
                } finally {
                    FileUtils.closeStream(in);
                }
                return "";
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
        log.debug(e);
        throw AxisFault.makeFault(e);
    }
    if (log.isDebugEnabled())
        log.debug(Messages.getMessage("exit00", "CommonsHTTPSender::invoke"));
}

From source file:org.elasticsearch.client.SearchIT.java

@Before
public void indexDocuments() throws IOException {
    StringEntity doc1 = new StringEntity("{\"type\":\"type1\", \"num\":10, \"num2\":50}",
            ContentType.APPLICATION_JSON);
    client().performRequest(HttpPut.METHOD_NAME, "/index/type/1", Collections.emptyMap(), doc1);
    StringEntity doc2 = new StringEntity("{\"type\":\"type1\", \"num\":20, \"num2\":40}",
            ContentType.APPLICATION_JSON);
    client().performRequest(HttpPut.METHOD_NAME, "/index/type/2", Collections.emptyMap(), doc2);
    StringEntity doc3 = new StringEntity("{\"type\":\"type1\", \"num\":50, \"num2\":35}",
            ContentType.APPLICATION_JSON);
    client().performRequest(HttpPut.METHOD_NAME, "/index/type/3", Collections.emptyMap(), doc3);
    StringEntity doc4 = new StringEntity("{\"type\":\"type2\", \"num\":100, \"num2\":10}",
            ContentType.APPLICATION_JSON);
    client().performRequest(HttpPut.METHOD_NAME, "/index/type/4", Collections.emptyMap(), doc4);
    StringEntity doc5 = new StringEntity("{\"type\":\"type2\", \"num\":100, \"num2\":10}",
            ContentType.APPLICATION_JSON);
    client().performRequest(HttpPut.METHOD_NAME, "/index/type/5", Collections.emptyMap(), doc5);
    client().performRequest(HttpPost.METHOD_NAME, "/index/_refresh");

    StringEntity doc = new StringEntity("{\"field\":\"value1\", \"rating\": 7}", ContentType.APPLICATION_JSON);
    client().performRequest(HttpPut.METHOD_NAME, "/index1/doc/1", Collections.emptyMap(), doc);
    doc = new StringEntity("{\"field\":\"value2\"}", ContentType.APPLICATION_JSON);
    client().performRequest(HttpPut.METHOD_NAME, "/index1/doc/2", Collections.emptyMap(), doc);

    StringEntity mappings = new StringEntity(
            "{" + "  \"mappings\": {" + "    \"doc\": {" + "      \"properties\": {" + "        \"rating\": {"
                    + "          \"type\":  \"keyword\"" + "        }" + "      }" + "    }" + "  }" + "}}",
            ContentType.APPLICATION_JSON);
    client().performRequest("PUT", "/index2", Collections.emptyMap(), mappings);
    doc = new StringEntity("{\"field\":\"value1\", \"rating\": \"good\"}", ContentType.APPLICATION_JSON);
    client().performRequest(HttpPut.METHOD_NAME, "/index2/doc/3", Collections.emptyMap(), doc);
    doc = new StringEntity("{\"field\":\"value2\"}", ContentType.APPLICATION_JSON);
    client().performRequest(HttpPut.METHOD_NAME, "/index2/doc/4", Collections.emptyMap(), doc);

    doc = new StringEntity("{\"field\":\"value1\"}", ContentType.APPLICATION_JSON);
    client().performRequest(HttpPut.METHOD_NAME, "/index3/doc/5", Collections.emptyMap(), doc);
    doc = new StringEntity("{\"field\":\"value2\"}", ContentType.APPLICATION_JSON);
    client().performRequest(HttpPut.METHOD_NAME, "/index3/doc/6", Collections.emptyMap(), doc);
    client().performRequest(HttpPost.METHOD_NAME, "/index1,index2,index3/_refresh");
}

From source file:com.seleritycorp.common.base.http.server.HttpRequest.java

/**
 * Checks if a request is a POST request.
 * /*from ww  w  . ja  v a2  s . c o m*/
 * @return true, if it is a POST request. false otherwise.
 */
public boolean isMethodPost() {
    return HttpPost.METHOD_NAME.equals(httpServletRequest.getMethod());
}

From source file:com.googlecode.libautocaptcha.tools.VodafoneItalyTool.java

private void initHttpClient() {
    httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Mozilla/5.0");
    httpClient.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
    httpClient.setCookieStore(new BasicCookieStore());
    httpClient.setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override//from  w ww. ja  v a  2  s . c  om
        public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                throws ProtocolException {
            boolean isRedirected = super.isRedirected(request, response, context);
            if (!isRedirected && request.getRequestLine().getMethod().equals(HttpPost.METHOD_NAME)
                    && response.getStatusLine().getStatusCode() == 302)
                return true; // allow POST redirection
            return isRedirected;
        }
    });
}

From source file:org.elasticsearch.client.RequestConverters.java

static Request openIndex(OpenIndexRequest openIndexRequest) {
    String endpoint = endpoint(openIndexRequest.indices(), "_open");
    Request request = new Request(HttpPost.METHOD_NAME, endpoint);

    Params parameters = new Params(request);
    parameters.withTimeout(openIndexRequest.timeout());
    parameters.withMasterTimeout(openIndexRequest.masterNodeTimeout());
    parameters.withWaitForActiveShards(openIndexRequest.waitForActiveShards());
    parameters.withIndicesOptions(openIndexRequest.indicesOptions());
    return request;
}

From source file:org.jtalks.poulpe.service.JcommuneHttpNotifier.java

/**
 * Notifies reindex ?omponent/*from w w  w. j  a  v  a2 s . c o  m*/
 *
 * @param jCommuneUrl JCommune Url
 * @throws NoConnectionToJcommuneException
 *          some connection problems happened, while trying to notify Jcommune
 * @throws JcommuneRespondedWithErrorException
 *          occurs when the response status is not in the interval {@code MIN_HTTP_STATUS} and {@code
 *          MAX_HTTP_STATUS}
 * @throws org.jtalks.poulpe.service.exceptions.JcommuneUrlNotConfiguredException
 *          occurs when the {@code jCommuneUrl} is incorrect
 */
public void notifyAboutReindexComponent(String jCommuneUrl) throws NoConnectionToJcommuneException,
        JcommuneRespondedWithErrorException, JcommuneUrlNotConfiguredException {
    checkUrlIsConfigured(jCommuneUrl);
    createAndSendRequest(jCommuneUrl + REINDEX_URL_PART, HttpPost.METHOD_NAME);
}

From source file:org.elasticsearch.client.RequestConverters.java

static Request closeIndex(CloseIndexRequest closeIndexRequest) {
    String endpoint = endpoint(closeIndexRequest.indices(), "_close");
    Request request = new Request(HttpPost.METHOD_NAME, endpoint);

    Params parameters = new Params(request);
    parameters.withTimeout(closeIndexRequest.timeout());
    parameters.withMasterTimeout(closeIndexRequest.masterNodeTimeout());
    parameters.withIndicesOptions(closeIndexRequest.indicesOptions());
    return request;
}

From source file:com.amos.tool.SelfRedirectStrategy.java

public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response,
        final HttpContext context) throws ProtocolException {
    final URI uri = getLocationURI(request, response, context);
    final String method = request.getRequestLine().getMethod();
    if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) {
        return new HttpHead(uri);
    } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) {
        return new HttpGet(uri);
    } else if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
        return new HttpPost(uri);
    } else {/*from w ww. ja  v a 2s.c  o  m*/
        final int status = response.getStatusLine().getStatusCode();
        if (status == HttpStatus.SC_TEMPORARY_REDIRECT) {
            return RequestBuilder.copy(request).setUri(uri).build();
        } else {
            return new HttpGet(uri);
        }
    }
}

From source file:com.clickntap.vimeo.Vimeo.java

public String addTextTrack(String videoEndPoint, File file, boolean active, String type, String language,
        String name) throws IOException, VimeoException {

    VimeoResponse response = null;//from   w  ww.j av a 2s.  c  om

    Map<String, String> params = new HashMap<String, String>();
    params.put("active", active ? "true" : "false");
    params.put("type", type);
    params.put("language", language);
    params.put("name", name);

    VimeoResponse addVideoRespose = apiRequest(new StringBuffer(videoEndPoint).append("/texttracks").toString(),
            HttpPost.METHOD_NAME, params, null);

    if (addVideoRespose.getStatusCode() == 201) {
        String textTrackUploadLink = addVideoRespose.getJson().getString("link");
        response = apiRequest(textTrackUploadLink, HttpPut.METHOD_NAME, null, file);
        if (response.getStatusCode() == 200) {
            return addVideoRespose.getJson().getString("uri");
        }
    }
    throw new VimeoException(
            new StringBuffer("HTTP Status Code: ").append(response.getStatusCode()).toString());

}

From source file:com.azure.webapi.MobileServiceClient.java

/**
 * Invokes a custom API using POST HTTP method
 * //from w ww. ja  v a  2 s .c o m
 * @param apiName
 *            The API name
 * @param clazz
 *            The API result class
 * @param callback
 *            The callback to invoke after the API execution
 */
public <E> void invokeApi(String apiName, Class<E> clazz, ApiOperationCallback<E> callback) {
    invokeApi(apiName, null, HttpPost.METHOD_NAME, null, clazz, callback);
}