Example usage for org.apache.commons.httpclient.methods PostMethod setRequestEntity

List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestEntity

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods PostMethod setRequestEntity.

Prototype

public void setRequestEntity(RequestEntity paramRequestEntity) 

Source Link

Usage

From source file:com.google.wave.api.robot.HttpRobotConnection.java

@Override
public String postJson(String url, String body) throws RobotConnectionException {
    PostMethod method = new PostMethod(url);
    try {//w  ww.j  a v  a2  s  . co m
        method.setRequestEntity(
                new StringRequestEntity(body, RobotConnection.JSON_CONTENT_TYPE, Charsets.UTF_8.name()));
        return fetch(url, method);
    } catch (IOException e) {
        String msg = "Robot fetch http failure: " + url + ": " + e;
        throw new RobotConnectionException(msg, e);
    }
}

From source file:edu.stanford.muse.slant.CustomSearchHelper.java

/** pushes the given xml to the user's CSE configuration 
 * @throws IOException //  w  ww. ja v a 2 s. c o m
 * @throws HttpException */
public static boolean pushAnnotations(String authtoken, String xml) throws HttpException, IOException {
    // see http://code.google.com/apis/customsearch/docs/api.html#create_annos

    HttpClient client = new HttpClient();
    PostMethod annotation_post = new PostMethod("http://www.google.com/coop/api/default/annotations/");

    log.debug("uploading annotations:\n" + xml);
    annotation_post.addRequestHeader("Content-type", "text/xml");
    annotation_post.addRequestHeader("Authorization", "GoogleLogin auth=" + authtoken);
    StringRequestEntity rq_en = new StringRequestEntity(xml, "text/xml", "UTF-8");
    annotation_post.setRequestEntity(rq_en);

    int astatusCode = client.executeMethod(annotation_post);
    if (astatusCode == HttpStatus.SC_OK)
        return true;
    else {
        String responseBody = IOUtils.toString(annotation_post.getResponseBodyAsStream(), "UTF-8");
        log.warn("Annotation update failed: " + responseBody);
        return false;
    }
}

From source file:com.linkedin.pinot.server.realtime.ServerSegmentCompletionProtocolHandler.java

private SegmentCompletionProtocol.Response doHttp(SegmentCompletionProtocol.Request request, Part[] parts) {
    SegmentCompletionProtocol.Response response = new SegmentCompletionProtocol.Response(
            SegmentCompletionProtocol.ControllerResponseStatus.NOT_SENT, -1L);
    HttpClient httpClient = new HttpClient();
    ControllerLeaderLocator leaderLocator = ControllerLeaderLocator.getInstance();
    final String leaderAddress = leaderLocator.getControllerLeader();
    if (leaderAddress == null) {
        LOGGER.error("No leader found {}", this.toString());
        return new SegmentCompletionProtocol.Response(
                SegmentCompletionProtocol.ControllerResponseStatus.NOT_LEADER, -1L);
    }//from   w ww.  ja  v  a  2 s.c  om
    final String url = request.getUrl(leaderAddress);
    HttpMethodBase method;
    if (parts != null) {
        PostMethod postMethod = new PostMethod(url);
        postMethod.setRequestEntity(new MultipartRequestEntity(parts, new HttpMethodParams()));
        method = postMethod;
    } else {
        method = new GetMethod(url);
    }
    LOGGER.info("Sending request {} for {}", url, this.toString());
    try {
        int responseCode = httpClient.executeMethod(method);
        if (responseCode >= 300) {
            LOGGER.error("Bad controller response code {} for {}", responseCode, this.toString());
            return response;
        } else {
            response = new SegmentCompletionProtocol.Response(method.getResponseBodyAsString());
            LOGGER.info("Controller response {} for {}", response.toJsonString(), this.toString());
            if (response.getStatus().equals(SegmentCompletionProtocol.ControllerResponseStatus.NOT_LEADER)) {
                leaderLocator.refreshControllerLeader();
            }
            return response;
        }
    } catch (IOException e) {
        LOGGER.error("IOException {}", this.toString(), e);
        leaderLocator.refreshControllerLeader();
        return response;
    }
}

From source file:com.github.rnewson.couchdb.lucene.Database.java

private String post(final String path, final String body) throws HttpException, IOException {
    final PostMethod post = new PostMethod(url(path));
    post.setRequestEntity(new StringRequestEntity(body, "application/json", "UTF-8"));
    return execute(post);
}

From source file:com.taobao.metamorphosis.client.http.SimpleHttpProducer.java

/**
 * // www .  j  av  a 2 s .c  om
 * 
 * @param message
 * @throws MetaClientException
 */
public SendResult sendMessage(final Message message, final Partition partition) throws MetaClientException {
    final long start = System.currentTimeMillis();
    this.checkMessage(message);
    final int flag = MessageFlagUtils.getFlag(message);
    final byte[] data = SimpleMessageProducer.encodeData(message);
    final String uri = "/put/" + partition.getBrokerId() + "?topic=" + message.getTopic() + "&partition="
            + partition.getPartition() + "&flag=" + flag + "&length=" + data.length;
    final PostMethod postMethod = new PostMethod(uri);
    try {
        postMethod.setRequestEntity(new ByteArrayRequestEntity(data));
        this.httpclient.executeMethod(postMethod);
        final String resultStr = postMethod.getResponseBodyAsString();
        switch (postMethod.getStatusCode()) {
        case HttpStatus.Success: {
            // messageId partition offset
            final String[] tmps = RESULT_SPLITER.split(resultStr);
            // idid
            MessageAccessor.setId(message, Long.parseLong(tmps[0]));
            return new SendResult(true, new Partition(0, Integer.parseInt(tmps[1])), Long.parseLong(tmps[2]),
                    null);
        }
        case HttpStatus.Forbidden: {
            // ,
            return new SendResult(false, null, -1, String.valueOf(HttpStatus.Forbidden));
        }
        default:
            return new SendResult(false, null, -1, resultStr);
        }
    } catch (final Exception e) {
        this.logger.error(e.getMessage(), e);
        throw new MetaClientException(e);
    } finally {
        final long duration = System.currentTimeMillis() - start;
        System.out.println(duration);
        MetaStatLog.addStatValue2(null, StatConstants.PUT_TIME_STAT, message.getTopic(), duration);
        postMethod.releaseConnection();
    }

}

From source file:com.predic8.membrane.core.transport.http.InterceptorInvocationTest.java

private PostMethod createPostMethod() {
    PostMethod post = new PostMethod("http://localhost:4000/axis2/services/BLZService");
    post.setRequestEntity(new InputStreamRequestEntity(this.getClass().getResourceAsStream("/getBank.xml")));
    post.setRequestHeader(Header.CONTENT_TYPE, MimeType.TEXT_XML_UTF8);
    post.setRequestHeader(Header.SOAP_ACTION, "");
    return post;/*from  ww  w.  j a  v  a 2s  . c  o  m*/
}

From source file:PublisherUtil.java

/**
 * Publishes a list of files and a datasource to the server with basic authentication to the server
 * /* w w w .  ja  va 2 s .  c o m*/
 * @param publishURL
 *          The URL of the Pentaho server
 * @param publishPath
 *          The path in the solution to place the files
 * @param publishFiles
 *          Array of File objects to post to the server
 * @param dataSource
 *          The datasource to publish to the server
 * @param publishPassword
 *          The publishing password for the server
 * @param serverUserid
 *          The userid to authenticate to the server
 * @param serverPassword
 *          The password to authenticate with the server
 * @param overwrite
 *          Whether the server should overwrite the file if it exists already
 * @param mkdirs
 *          Whether the server should create any missing folders on the publish path
 * @return Server response as a string
* @throws Exception 
 */
public static String publish(final String publishURL, final String publishPath, final File publishFiles[],
        final String publishPassword, final String serverUserid, final String serverPassword,
        final boolean overwrite, final boolean mkdirs) throws Exception {
    int status = -1;
    System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); //$NON-NLS-1$ //$NON-NLS-2$
    System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true"); //$NON-NLS-1$ //$NON-NLS-2$
    System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire.header", "warn");//$NON-NLS-1$ //$NON-NLS-2$
    System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "warn");//$NON-NLS-1$ //$NON-NLS-2$

    String fullURL = null;
    try {
        fullURL = publishURL + "?publishPath=" + URLEncoder.encode(publishPath, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        fullURL = publishURL + "?publishPath=" + publishPath;
        System.out.println("Erro de publicao na classe publisher!" + e);
        // throw new Exception("Erro de publicao na classe publisher!" + e);
    }
    if (publishPassword == null) {
        throw new IllegalArgumentException("PUBLISHERUTIL.ERROR_0001_PUBLISH_PASSWORD_REQUIRED"); //$NON-NLS-1$
        // throw new IllegalArgumentException(Messages.getErrorString("PUBLISHERUTIL.ERROR_0001_PUBLISH_PASSWORD_REQUIRED")); //$NON-NLS-1$
    }

    fullURL += "&publishKey=" + PublisherUtil.getPasswordKey(publishPassword); //$NON-NLS-1$
    fullURL += "&overwrite=" + overwrite; //$NON-NLS-1$
    fullURL += "&mkdirs=" + mkdirs; //$NON-NLS-1$

    PostMethod filePost = new PostMethod(fullURL);

    Part[] parts = new Part[publishFiles.length];
    for (int i = 0; i < publishFiles.length; i++) {
        try {
            File file = publishFiles[i];
            FileInputStream in = new FileInputStream(file);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            IOUtils.copy(in, out);
            String reportNameEncoded = (URLEncoder.encode(file.getName(), "UTF-8"));
            ByteArrayPartSource source = new ByteArrayPartSource(reportNameEncoded, out.toByteArray());
            parts[i] = new FilePart(reportNameEncoded, source, FilePart.DEFAULT_CONTENT_TYPE, "UTF-8");
        } catch (Exception e) {
            PublisherUtil.logger.error(null, e);
            throw new Exception("Erro de publicao na classe publisher!" + e);
        }
    }

    filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
    HttpClient client = new HttpClient();

    try {
        if ((serverUserid != null) && (serverUserid.length() > 0) && (serverPassword != null)
                && (serverPassword.length() > 0)) {
            Credentials creds = new UsernamePasswordCredentials(serverUserid, serverPassword);
            client.getState().setCredentials(AuthScope.ANY, creds);
            client.getParams().setAuthenticationPreemptive(true);
        }
        status = client.executeMethod(filePost);

        if (status == HttpStatus.SC_OK) {
            String postResult = filePost.getResponseBodyAsString();

            if (postResult != null) {
                try {
                    return postResult.trim(); // +" - "+Integer.parseInt(postResult.trim());
                } catch (NumberFormatException e) {
                    PublisherUtil.logger.error(null, e);
                    // throw new Exception("Erro de publicao na classe publisher!" + e + " " +PublisherUtil.FILE_ADD_INVALID_USER_CREDENTIALS);
                    return "" + PublisherUtil.FILE_ADD_INVALID_USER_CREDENTIALS;
                }
            }
        } else if (status == HttpStatus.SC_UNAUTHORIZED) {
            return "" + PublisherUtil.FILE_ADD_INVALID_USER_CREDENTIALS;
        }
    } catch (HttpException e) {
        PublisherUtil.logger.error(null, e);
        // throw new Exception("Erro de publicao na classe publisher!" + e );
    } catch (IOException e) {
        PublisherUtil.logger.error(null, e);
        // throw new Exception("Erro de publicao na classe publisher!" + e );
    }
    // return Messages.getString("REPOSITORYFILEPUBLISHER.USER_PUBLISHER_FAILED"); //$NON-NLS-1$
    return "" + PublisherUtil.FILE_ADD_FAILED;
}

From source file:jenkins.plugins.elanceodesk.workplace.notifier.HttpWorker.java

public void run() {
    int tried = 0;
    boolean success = false;
    HttpClient client = getHttpClient();
    client.getParams().setConnectionManagerTimeout(timeout);
    do {//from  www. j  a v a2 s  .c  o  m
        tried++;
        RequestEntity requestEntity;
        try {
            requestEntity = new StringRequestEntity(data, "application/json", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace(logger);
            break;
        }
        logger.println(String.format("Posting data to webhook - %s. Already Tried %s times", url, tried));
        PostMethod post = new PostMethod(url);
        try {
            post.setRequestEntity(requestEntity);
            int responseCode = client.executeMethod(post);
            if (responseCode != HttpStatus.SC_OK) {
                String response = post.getResponseBodyAsString();
                logger.println(String.format(
                        "Posting data to - %s may have failed. Webhook responded with status code - %s", url,
                        responseCode));
                logger.println(String.format("Message from webhook - %s", response));

            } else {
                success = true;
                logger.println(String.format("Posting data to webhook - %s completed ", url));
            }
        } catch (Exception e) {
            logger.println(String.format("Failed to post data to webhook - %s", url));
            e.printStackTrace(logger);
        } finally {
            post.releaseConnection();
        }
    } while (tried < retries && !success);

}

From source file:com.apatar.core.ApatarHttpClient.java

public String sendPostHttpQuery(String url, HashMap<String, String> params) throws IOException {
    int size = params.size();
    Part[] parts = new Part[size];
    int i = 0;//from  w ww. j ava  2 s .  com
    for (String param : params.keySet()) {
        parts[i++] = new StringPart(param, params.get(param));
    }

    PostMethod method = new PostMethod(url);

    method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));

    return sendHttpQuery(method);

}

From source file:com.calclab.emite.xtesting.services.HttpConnector.java

private Runnable createSendAction(final String httpBase, final String xml, final ConnectorCallback callback) {
    return new Runnable() {
        public void run() {
            final String id = HttpConnectorID.getNext();
            debug("Connector [{0}] send: {1}", id, xml);
            final HttpClientParams params = new HttpClientParams();
            params.setConnectionManagerTimeout(10000);
            final HttpClient client = new HttpClient(params);
            int status = 0;
            String response = null;
            final PostMethod post = new PostMethod(httpBase);

            try {
                post.setRequestEntity(new StringRequestEntity(xml, "text/xml", "utf-8"));
                System.out.println("SENDING: " + xml);
                status = client.executeMethod(post);
                response = post.getResponseBodyAsString();
            } catch (final Exception e) {
                callback.onError(xml, e);
                e.printStackTrace();//  w w w.j  a v  a  2s  . com
            } finally {
                post.releaseConnection();
            }

            receiveService.execute(createResponseAction(xml, callback, id, status, response));
        }
    };
}