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

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

Introduction

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

Prototype

public PostMethod(String paramString) 

Source Link

Usage

From source file:edu.virginia.speclab.juxta.author.view.export.WebServiceClient.java

/**
 * Attempt to authenticate a user at the specified base rl
 * @param serviceUrl//from  w ww  .  jav  a  2 s .  c o m
 * @param email
 * @param pass
 * @return The workspace or null
 */
public boolean authenticate(final String email, final String pass) throws IOException {
    this.httpClient = newHttpClient();

    PostMethod post = new PostMethod(this.baseUrl + "/import/authenticate");
    NameValuePair[] data = { new NameValuePair("email", email), new NameValuePair("password", pass) };
    post.setRequestBody(data);

    // exec with a false to prevent a throw on non-200 resp
    int respCode = execRequest(post, false);
    if (respCode == 200) {
        String resp = getResponseString(post);
        JsonParser parser = new JsonParser();
        JsonObject obj = parser.parse(resp).getAsJsonObject();
        this.authToken = obj.get("token").getAsString();
        post.releaseConnection();
        return true;
    } else if (respCode == 401) {
        // bad credentials
        post.releaseConnection();
    } else {
        // smething else bad. just throw it
        post.releaseConnection();
        throw new IOException("Service Error (code " + respCode + ")");
    }

    return false;
}

From source file:com.mindquarry.common.index.SolrIndexClient.java

private void sendToIndexer(byte[] content) throws Exception {
    PostMethod pMethod = new PostMethod(solrEndpoint);
    pMethod.setDoAuthentication(true);//w ww  .j  a  v a 2 s  . c o  m
    pMethod.addRequestHeader("accept", "text/xml"); //$NON-NLS-1$ //$NON-NLS-2$
    pMethod.setRequestEntity(new ByteArrayRequestEntity(content));

    try {
        httpClient.executeMethod(pMethod);
    } finally {
        pMethod.releaseConnection();
    }

    if (pMethod.getStatusCode() == 200) {
        // everything worked fine, nothing more to do
    } else if (pMethod.getStatusCode() == 401) {
        getLogger().warn("Authorization problem. Could not connect to index updater.");
    } else {
        System.out.println("Unknown error");
        System.out.println("STATUS: " + pMethod.getStatusCode());
        System.out.println("RESPONSE: " + pMethod.getResponseBodyAsString());
    }
    pMethod.releaseConnection();
}

From source file:net.neurowork.cenatic.centraldir.workers.XMLPushTest.java

private void pushOrganization(String token) {
    PostMethod post = new PostMethod(restUrl.getPushOrganizationUrl());

    NameValuePair tokenParam = new NameValuePair("token", token);
    NameValuePair[] params = new NameValuePair[] { tokenParam };

    post.addRequestHeader("Accept", "application/xml");
    post.setQueryString(params);//from   www . j  a v  a  2s.  c o  m
    post.setRequestBody(XmlPushCreator.getInstance().getPushXml(organizacion));

    try {
        int result = httpclient.executeMethod(post);
        logger.info("Response status code: " + result);
        logger.info("Response body: ");
        logger.info(post.getResponseBodyAsString());
    } catch (HttpException e) {
        logger.error(e.getMessage());
    } catch (IOException e) {
        logger.error(e.getMessage());
    } finally {
        post.releaseConnection();
    }

}

From source file:es.carebear.rightmanagement.client.RestClient.java

public void getAllRigthsOfGroups() throws IOException {
    HttpClient client = new HttpClient();

    PostMethod deleteMethod = new PostMethod(getServiceBaseURI() + "/client/groups/all/rights/" + "Moderator");

    deleteMethod.addParameter("authName", "Admin");

    int responseCode = client.executeMethod(deleteMethod);

    String response = responseToString(deleteMethod.getResponseBodyAsStream());

    System.out.println(responseCode);

}

From source file:net.mojodna.searchable.solr.SolrIndexer.java

@Override
public void optimize() throws IndexingException {
    try {//from  w w w .j  a va2 s  . c  o m
        PostMethod post = new PostMethod(solrPath);
        post.setRequestEntity(new StringRequestEntity("<optimize waitFlush=\"false\" waitSearcher=\"false\"/>",
                "text/xml", "UTF-8"));
        log.debug("Optimizing.");
        getHttpClient().executeMethod(post);
    } catch (final IOException e) {
        throw new IndexingException(e);
    }
}

From source file:com.cloud.network.bigswitch.BigSwitchBcfApi.java

protected HttpMethod createMethod(final String type, final String uri, final int port)
        throws BigSwitchBcfApiException {
    String url;//from   w  ww.j  a  v a2s . c o m
    try {
        url = new URL(S_PROTOCOL, host, port, uri).toString();
    } catch (MalformedURLException e) {
        S_LOGGER.error("Unable to build Big Switch API URL", e);
        throw new BigSwitchBcfApiException("Unable to build Big Switch API URL", e);
    }

    if ("post".equalsIgnoreCase(type)) {
        return new PostMethod(url);
    } else if ("get".equalsIgnoreCase(type)) {
        return new GetMethod(url);
    } else if ("delete".equalsIgnoreCase(type)) {
        return new DeleteMethod(url);
    } else if ("put".equalsIgnoreCase(type)) {
        return new PutMethod(url);
    } else {
        throw new BigSwitchBcfApiException("Requesting unknown method type");
    }
}

From source file:com.benfante.jslideshare.SlideShareConnectorImpl.java

public InputStream sendMessage(String url, Map<String, String> parameters)
        throws IOException, SlideShareErrorException {
    HttpClient client = createHttpClient();
    PostMethod method = new PostMethod(url);
    method.addParameter("api_key", this.apiKey);
    Iterator<Map.Entry<String, String>> entryIt = parameters.entrySet().iterator();
    while (entryIt.hasNext()) {
        Map.Entry<String, String> entry = entryIt.next();
        method.addParameter(entry.getKey(), entry.getValue());
    }// w  w w  . j  ava2s .  com
    Date now = new Date();
    String ts = Long.toString(now.getTime() / 1000);
    String hash = DigestUtils.shaHex(this.sharedSecret + ts).toLowerCase();
    method.addParameter("ts", ts);
    method.addParameter("hash", hash);
    logger.debug("Sending POST message to " + method.getURI().getURI() + " with parameters "
            + Arrays.toString(method.getParameters()));
    int statusCode = client.executeMethod(method);
    if (statusCode != HttpStatus.SC_OK) {
        logger.debug("Server replied with a " + statusCode + " HTTP status code ("
                + HttpStatus.getStatusText(statusCode) + ")");
        throw new SlideShareErrorException(statusCode, HttpStatus.getStatusText(statusCode));
    }
    if (logger.isDebugEnabled()) {
        logger.debug(method.getResponseBodyAsString());
    }
    InputStream result = new ByteArrayInputStream(method.getResponseBody());
    method.releaseConnection();
    return result;
}

From source file:com.duowan.common.rpc.client.CommonsHttpInvokerRequestExecutor.java

/**
 * Create a PostMethod for the given configuration.
 * <p>The default implementation creates a standard PostMethod with
 * "application/x-java-serialized-object" as "Content-Type" header.
 * @param config the HTTP invoker configuration that specifies the
 * target service/*from   w  w w. java2s. c  om*/
 * @return the PostMethod instance
 * @throws IOException if thrown by I/O methods
 */
protected PostMethod createPostMethod(String serviceUrl) throws IOException {
    PostMethod postMethod = new PostMethod(serviceUrl);
    LocaleContext locale = LocaleContextHolder.getLocaleContext();
    if (locale != null) {
        postMethod.addRequestHeader(HTTP_HEADER_ACCEPT_LANGUAGE, StringUtils.toLanguageTag(locale.getLocale()));
    }
    if (isAcceptGzipEncoding()) {
        postMethod.addRequestHeader(HTTP_HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
    }
    return postMethod;
}

From source file:com.feilong.tools.net.httpclient3.HttpClientUtil.java

/**
 *  uri and params./*from   w  w  w .ja v  a2  s .  co m*/
 *
 * @param httpClientConfig
 *            the uri and params
 * @return the http method
 * @since 1.0.9
 */
private static HttpMethod setUriAndParams(HttpClientConfig httpClientConfig) {

    String uri = httpClientConfig.getUri();

    Map<String, String> params = httpClientConfig.getParams();

    NameValuePair[] nameValuePairs = null;
    if (Validator.isNotNullOrEmpty(params)) {
        nameValuePairs = NameValuePairUtil.fromMap(params);
    }

    HttpMethodType httpMethodType = httpClientConfig.getHttpMethodType();
    switch (httpMethodType) {

    case GET: // get
        GetMethod getMethod = new GetMethod(uri);

        //TODO ?? uri??  nameValuePairs
        if (Validator.isNotNullOrEmpty(nameValuePairs) && uri.indexOf("?") != -1) {
            throw new NotImplementedException("not implemented!");
        }

        if (Validator.isNotNullOrEmpty(nameValuePairs)) {
            getMethod.setQueryString(nameValuePairs);
        }
        return getMethod;

    case POST: // post
        PostMethod postMethod = new PostMethod(uri);

        if (Validator.isNotNullOrEmpty(nameValuePairs)) {
            postMethod.setRequestBody(nameValuePairs);
        }
        return postMethod;
    default:
        throw new UnsupportedOperationException("httpMethod:[" + httpMethodType + "] not support!");
    }
}

From source file:edu.uci.ics.external.connector.asterixdb.ConnectorUtils.java

public static void cleanDataset(StorageParameter storageParameter, DatasetInfo datasetInfo) throws Exception {
    // DDL service URL.
    String url = storageParameter.getServiceURL() + "/ddl";
    // Builds the DDL string to delete and (re-)create the sink datset.
    StringBuilder ddlBuilder = new StringBuilder();
    // use dataverse statement.
    ddlBuilder.append("use dataverse ");
    ddlBuilder.append(storageParameter.getDataverseName());
    ddlBuilder.append(";");

    // drop dataset statement.
    ddlBuilder.append("drop dataset ");
    ddlBuilder.append(storageParameter.getDatasetName());
    ddlBuilder.append(";");

    // create datset statement.
    ddlBuilder.append("create temporary dataset ");
    ddlBuilder.append(storageParameter.getDatasetName());
    ddlBuilder.append("(");
    ddlBuilder.append(datasetInfo.getRecordType().getTypeName());
    ddlBuilder.append(")");
    ddlBuilder.append(" primary key ");
    for (String primaryKey : datasetInfo.getPrimaryKeyFields()) {
        ddlBuilder.append(primaryKey);/*ww  w.  j  a  v  a2 s .  c o m*/
        ddlBuilder.append(",");
    }
    ddlBuilder.delete(ddlBuilder.length() - 1, ddlBuilder.length());
    ddlBuilder.append(";");

    // Create a method instance.
    PostMethod method = new PostMethod(url);
    method.setRequestEntity(new StringRequestEntity(ddlBuilder.toString()));
    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    // Execute the method.
    executeHttpMethod(method);
}