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

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

Introduction

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

Prototype

public void setRequestBody(NameValuePair[] paramArrayOfNameValuePair) throws IllegalArgumentException 

Source Link

Usage

From source file:com.serena.rlc.jenkins.plugins.rlcnotifier.RLCSite.java

public String executeJSONPost(URI uri, String postContents) throws Exception {
    String result = null;/* w w w . j  av  a  2s . com*/
    HttpClient httpClient = new HttpClient();

    if ("https".equalsIgnoreCase(uri.getScheme())) {
        ProtocolSocketFactory socketFactory = new OpenSSLProtocolSocketFactory();
        Protocol https = new Protocol("https", socketFactory, 443);
        Protocol.registerProtocol("https", https);
    }

    PostMethod method = new PostMethod(uri.toString());
    if (postContents != null)
        method.setRequestBody(postContents);
    method.setRequestHeader("Content-Type", "application/json");
    method.setRequestHeader("charset", "utf-8");
    try {
        HttpClientParams params = httpClient.getParams();
        params.setAuthenticationPreemptive(true);

        UsernamePasswordCredentials clientCredentials = new UsernamePasswordCredentials(user, password);
        httpClient.getState().setCredentials(AuthScope.ANY, clientCredentials);

        int responseCode = httpClient.executeMethod(method);

        if (responseCode != 200) {
            throw new Exception("Serena RLC returned error code: " + responseCode);
        } else {
            result = method.getResponseBodyAsString();
        }
    } catch (Exception e) {
        throw new Exception("Error connecting to Serena RLC: " + e.getMessage());
    } finally {
        method.releaseConnection();
    }

    return result;
}

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

/**
 * Attempt to authenticate a user at the specified base rl
 * @param serviceUrl//w ww  .j  ava2 s.  com
 * @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.sapienter.jbilling.client.api.APITest.java

License:asdf

private String[] makeCall(NameValuePair[] data, String separator) throws HttpException, IOException {

    Credentials creds = null;/* ww  w  . ja v a  2  s  .c  om*/
    //            creds = new UsernamePasswordCredentials(args[1], args[2]);

    //create a singular HttpClient object
    HttpClient client = new HttpClient();
    client.setConnectionTimeout(5000);

    //set the default credentials
    if (creds != null) {
        client.getState().setCredentials(null, null, creds);
    }

    PostMethod post = new PostMethod("http://localhost/betty/gateway");

    post.setRequestBody(data);

    //execute the method
    String responseBody = null;
    client.executeMethod(post);
    responseBody = post.getResponseBodyAsString();

    System.out.println("Got response:" + responseBody);
    //write out the response body
    //clean up the connection resources
    post.releaseConnection();
    post.recycle();

    return responseBody.split(separator, -1);
}

From source file:com.itude.mobile.mobbl.server.http.HttpDelegate.java

public HttpResponse connectPost(String url, String userAgent, ArrayList<Cookie> reqCookies,
        NameValuePair[] postData, Header[] requestHeaders, boolean followRedirects) {
    logger.debug("HttpDelegate.connectPost(): " + url);

    PostMethod post = new PostMethod(url);
    try {//  w w w . ja  v a2  s .c  o m
        prepareConnection(post, userAgent, reqCookies, requestHeaders, !url.contains("acceptxml=false"),
                followRedirects);
        if (postData != null)
            post.setRequestBody(postData);

        return executeHttpMethod(post);
    } catch (HttpException e) {
        logger.error(e.getMessage());
        logger.trace(e.getMessage(), e);
    } catch (IOException e) {
        logger.error(e.getMessage());
        logger.trace(e.getMessage(), e);
    } finally {
        post.releaseConnection();
    }

    return null;
}

From source file:edu.ku.brc.ui.FeedBackSender.java

/**
 * @param item/* w  w  w .  j av  a 2 s . c o  m*/
 * @throws Exception
 */
protected void send(final FeedBackSenderItem item) throws Exception {
    if (item != null) {
        // check the website for the info about the latest version
        HttpClient httpClient = new HttpClient();
        httpClient.getParams().setParameter("http.useragent", getClass().getName()); //$NON-NLS-1$

        PostMethod postMethod = new PostMethod(getSenderURL());

        // get the POST parameters (which includes usage stats, if we're allowed to send them)
        NameValuePair[] postParams = createPostParameters(item);
        postMethod.setRequestBody(postParams);

        // connect to the server
        try {
            httpClient.executeMethod(postMethod);

            // get the server response
            String responseString = postMethod.getResponseBodyAsString();

            if (StringUtils.isNotEmpty(responseString)) {
                System.err.println(responseString);
            }

        } catch (java.net.UnknownHostException uex) {
            log.error(uex.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:com.mirth.connect.client.core.UpdateClient.java

private List<UpdateInfo> getUpdatesFromUri(ServerInfo serverInfo) throws Exception {
    HttpClientParams httpClientParams = new HttpClientParams();
    HttpConnectionManager httpConnectionManager = new SimpleHttpConnectionManager();
    httpClientParams.setSoTimeout(10 * 1000);
    httpConnectionManager.getParams().setConnectionTimeout(10 * 1000);
    httpConnectionManager.getParams().setSoTimeout(10 * 1000);
    HttpClient httpClient = new HttpClient(httpClientParams, httpConnectionManager);

    PostMethod post = new PostMethod(client.getUpdateSettings().getUpdateUrl() + URL_UPDATES);
    NameValuePair[] params = { new NameValuePair("serverInfo", serializer.toXML(serverInfo)) };
    post.setRequestBody(params);

    try {/*from   ww w .  j ava2 s .  c om*/
        int statusCode = httpClient.executeMethod(post);

        if ((statusCode != HttpStatus.SC_OK) && (statusCode != HttpStatus.SC_MOVED_TEMPORARILY)) {
            throw new Exception("Failed to connect to update server: " + post.getStatusLine());
        }

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(post.getResponseBodyAsStream(), post.getResponseCharSet()));
        StringBuilder result = new StringBuilder();
        String input = new String();

        while ((input = reader.readLine()) != null) {
            result.append(input);
            result.append('\n');
        }

        return (List<UpdateInfo>) serializer.fromXML(result.toString());
    } catch (Exception e) {
        throw e;
    } finally {
        post.releaseConnection();
    }
}

From source file:de.avanux.livetracker.sender.LocationSender.java

private void sendPositionData(Configuration configuration, float lat, float lon) {
    String id = configuration.getID();
    log.debug("Using URL " + configuration.getPositionReceiverUrl());
    log.debug("Sending position data: id=" + id + " lat=" + lat + " lon=" + lon);
    PostMethod method = new PostMethod(configuration.getPositionReceiverUrl());
    NameValuePair[] data = { new NameValuePair(LocationMessage.TRACKING_ID, id),
            new NameValuePair(LocationMessage.LAT, "" + lat), new NameValuePair(LocationMessage.LON, "" + lon),
            new NameValuePair(LocationMessage.TIME, "" + System.currentTimeMillis()),
            new NameValuePair(LocationMessage.SPEED, "15") };
    method.setRequestBody(data);
    String response = executeHttpMethod(method);
    log.debug("Response: " + response);

    try {/*  w w w.  j av a 2 s.  co  m*/
        Configuration newConfiguration = new Configuration(response);
        log.debug("New min time interval: " + newConfiguration.getMinTimeInterval());
        configuration.setMinTimeInterval(newConfiguration.getMinTimeInterval());
        log.debug("Tracker count: " + newConfiguration.getTrackerCount());
    } catch (IOException e) {
        log.error("Error parsing configuration", e);
    }

}

From source file:com.khipu.lib.java.KhipuService.java

protected String post(Map data) throws KhipuJSONException, IOException {

    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(Khipu.API_URL + getMethodEndpoint());
    NameValuePair[] params = new NameValuePair[data.keySet().size()];

    int i = 0;//ww  w  .j  a  va 2 s  .co m
    for (Iterator iterator = data.keySet().iterator(); iterator.hasNext(); i++) {
        String key = (String) iterator.next();
        params[i] = new NameValuePair(key, (String) data.get(key));
    }

    postMethod.setRequestBody(params);

    postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    if (client.executeMethod(postMethod) == HttpStatus.SC_OK) {
        InputStream stream = postMethod.getResponseBodyAsStream();
        String contentAsString = getContentAsString(stream);
        stream.close();
        postMethod.releaseConnection();
        return contentAsString;
    }
    InputStream stream = postMethod.getResponseBodyAsStream();
    String contentAsString = getContentAsString(stream);
    stream.close();
    postMethod.releaseConnection();
    throw new KhipuJSONException(contentAsString);
}

From source file:mitm.common.security.ca.handlers.comodo.AutoAuthorize.java

/**
 * Authorizes the certificate with the given orderNummer. 
 * @return true if successful, false if an error occurs
 * @throws CustomClientCertException/*w ww  .j  a va 2  s  .co m*/
 */
public boolean authorize() throws CustomClientCertException {
    reset();

    if (StringUtils.isEmpty(loginName)) {
        throw new CustomClientCertException("loginName must be specified.");
    }

    if (StringUtils.isEmpty(loginPassword)) {
        throw new CustomClientCertException("loginPassword must be specified.");
    }

    if (StringUtils.isEmpty(orderNumber)) {
        throw new CustomClientCertException("orderNumber must be specified.");
    }

    PostMethod postMethod = new PostMethod(connectionSettings.getAutoAuthorizeURL());

    NameValuePair[] data = { new NameValuePair("loginName", loginName),
            new NameValuePair("loginPassword", loginPassword), new NameValuePair("orderNumber", orderNumber) };

    postMethod.setRequestBody(data);

    HTTPMethodExecutor executor = new HTTPMethodExecutor(connectionSettings.getTotalTimeout(),
            connectionSettings.getProxyInjector());

    executor.setConnectTimeout(connectionSettings.getConnectTimeout());
    executor.setReadTimeout(connectionSettings.getReadTimeout());

    try {
        executor.executeMethod(postMethod, responseHandler);
    } catch (IOException e) {
        throw new CustomClientCertException(e);
    }

    return !error;
}

From source file:com.urbancode.ds.jenkins.plugins.serenarapublisher.UrbanDeploySite.java

public String executeJSONPost(URI uri, String postContents) throws Exception {
    String result = null;/*from  w  ww .j av  a 2s.  c  o  m*/
    HttpClient httpClient = new HttpClient();

    if ("https".equalsIgnoreCase(uri.getScheme())) {
        ProtocolSocketFactory socketFactory = new OpenSSLProtocolSocketFactory();
        Protocol https = new Protocol("https", socketFactory, 443);
        Protocol.registerProtocol("https", https);
    }

    PostMethod method = new PostMethod(uri.toString());
    setDirectSsoInteractionHeader(method);
    method.setRequestBody(postContents);
    method.setRequestHeader("Content-Type", "application/json");
    method.setRequestHeader("charset", "utf-8");
    try {
        HttpClientParams params = httpClient.getParams();
        params.setAuthenticationPreemptive(true);

        UsernamePasswordCredentials clientCredentials = new UsernamePasswordCredentials(user, password);
        httpClient.getState().setCredentials(AuthScope.ANY, clientCredentials);

        int responseCode = httpClient.executeMethod(method);

        if (responseCode != 200) {
            throw new Exception("SerenaRA returned error code: " + responseCode);
        } else {
            result = method.getResponseBodyAsString();
        }
    } catch (Exception e) {
        throw new Exception("Error connecting to Serena DA: " + e.getMessage());
    } finally {
        method.releaseConnection();
    }

    return result;
}