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

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

Introduction

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

Prototype

public StringRequestEntity(String paramString1, String paramString2, String paramString3)
  throws UnsupportedEncodingException

Source Link

Usage

From source file:au.org.ala.biocache.web.AssertionController.java

/**
 * Generic method to post a record assertion notification.
 * @param type/*from w  w w .  ja  v  a2 s  .  co m*/
 * @param recordUuid
 * @param id
 * @deprecated assertion notifications are obtained through biocache ws NOT the collectory. This method should not be called.
 */
@Deprecated
private void postNotificationEvent(String type, String recordUuid, String id) {
    //get the processed record so that we can get the collection_uid
    FullRecord processed = Store.getByUuid(recordUuid, Versions.PROCESSED());
    if (processed == null) {
        processed = Store.getByRowKey(recordUuid, Versions.PROCESSED());
    }

    String uid = processed == null ? null : processed.getAttribution().getCollectionUid();

    if (uid != null) {
        final String uri = registryUrl + "/ws/notify";
        HttpClient h = new HttpClient();
        PostMethod m = new PostMethod(uri);

        try {
            m.setRequestEntity(new StringRequestEntity(
                    "{ event: 'user annotation', id: '" + id + "', uid: '" + uid + "', type:'" + type + "' }",
                    "text/json", "UTF-8"));

            logger.debug("Adding notification: " + type + ":" + uid + " - " + id);
            int status = h.executeMethod(m);
            logger.debug("STATUS: " + status);
            if (status == 200) {
                logger.debug("Successfully posted an event to the notification service");
            } else {
                logger.info("Failed to post an event to the notification service");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);

        }
    }
}

From source file:com.twinsoft.convertigo.engine.proxy.translated.HttpClient.java

private byte[] getData(HttpConnector connector, String resourceUrl, ParameterShuttle infoShuttle)
        throws IOException, EngineException {
    byte[] result = null;

    try {/*from  w  w  w .  j a v a2 s .c  o  m*/
        Context context = infoShuttle.context;

        String proxyServer = Engine.theApp.proxyManager.getProxyServer();
        String proxyUser = Engine.theApp.proxyManager.getProxyUser();
        String proxyPassword = Engine.theApp.proxyManager.getProxyPassword();
        int proxyPort = Engine.theApp.proxyManager.getProxyPort();

        HostConfiguration hostConfiguration = connector.hostConfiguration;

        boolean trustAllServerCertificates = connector.isTrustAllServerCertificates();

        // Retrieving httpState
        getHttpState(connector, infoShuttle);

        Engine.logEngine.trace("(HttpClient) Retrieving data as a bytes array...");
        Engine.logEngine.debug("(HttpClient) Connecting to: " + resourceUrl);

        // Proxy configuration
        if (!proxyServer.equals("")) {
            hostConfiguration.setProxy(proxyServer, proxyPort);
            Engine.logEngine.debug("(HttpClient) Using proxy: " + proxyServer + ":" + proxyPort);
        } else {
            // Remove old proxy configuration
            hostConfiguration.setProxyHost(null);
        }

        Engine.logEngine.debug("(HttpClient) Https: " + connector.isHttps());
        CertificateManager certificateManager = connector.certificateManager;

        URL url = null;
        String host = "";
        int port = -1;
        if (resourceUrl.toLowerCase().startsWith("https:")) {
            Engine.logEngine.debug("(HttpClient) Setting up SSL properties");
            certificateManager.collectStoreInformation(context);

            url = new URL(resourceUrl);
            host = url.getHost();
            port = url.getPort();
            if (port == -1)
                port = 443;

            Engine.logEngine.debug("(HttpClient) Host: " + host + ":" + port);

            Engine.logEngine
                    .debug("(HttpClient) CertificateManager has changed: " + certificateManager.hasChanged);
            if (certificateManager.hasChanged || (!host.equalsIgnoreCase(hostConfiguration.getHost()))
                    || (hostConfiguration.getPort() != port)) {
                Engine.logEngine.debug("(HttpClient) Using MySSLSocketFactory for creating the SSL socket");
                Protocol myhttps = new Protocol("https",
                        MySSLSocketFactory.getSSLSocketFactory(certificateManager.keyStore,
                                certificateManager.keyStorePassword, certificateManager.trustStore,
                                certificateManager.trustStorePassword, trustAllServerCertificates),
                        port);

                hostConfiguration.setHost(host, port, myhttps);
            }

            resourceUrl = url.getFile();
            Engine.logEngine.debug("(HttpClient) Updated URL for SSL purposes: " + resourceUrl);
        } else {
            url = new URL(resourceUrl);
            host = url.getHost();
            port = url.getPort();

            Engine.logEngine.debug("(HttpClient) Host: " + host + ":" + port);
            hostConfiguration.setHost(host, port);
        }

        Engine.logEngine.debug("(HttpClient) Building method on: " + resourceUrl);
        Engine.logEngine.debug("(HttpClient) postFromUser=" + infoShuttle.postFromUser);
        Engine.logEngine.debug("(HttpClient) postToSite=" + infoShuttle.postToSite);
        if (infoShuttle.postFromUser && infoShuttle.postToSite) {
            method = new PostMethod(resourceUrl);
            ((PostMethod) method).setRequestEntity(
                    new StringRequestEntity(infoShuttle.userPostData, infoShuttle.userContentType,
                            infoShuttle.context.httpServletRequest.getCharacterEncoding()));
        } else {
            method = new GetMethod(resourceUrl);
        }

        HttpMethodParams httpMethodParams = method.getParams();

        // Cookie configuration
        if (handleCookie) {
            Engine.logEngine.debug("(HttpClient) Setting cookie policy.");
            httpMethodParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        }

        String basicUser = connector.getAuthUser();
        String basicPassword = connector.getAuthPassword();
        String givenBasicUser = connector.getGivenAuthUser();
        String givenBasicPassword = connector.getGivenAuthPassword();

        // Basic authentication configuration
        String realm = null;
        if (!basicUser.equals("") || (basicUser.equals("") && (givenBasicUser != null))) {
            String userName = ((givenBasicUser == null) ? basicUser : givenBasicUser);
            String userPassword = ((givenBasicPassword == null) ? basicPassword : givenBasicPassword);
            httpState.setCredentials(new AuthScope(host, port, realm),
                    new UsernamePasswordCredentials(userName, userPassword));
            Engine.logEngine.debug("(HttpClient) Credentials: " + userName + ":******");
        }

        // Setting basic authentication for proxy
        if (!proxyServer.equals("") && !proxyUser.equals("")) {
            httpState.setProxyCredentials(new AuthScope(proxyServer, proxyPort),
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
            Engine.logEngine.debug("(HttpClient) Proxy credentials: " + proxyUser + ":******");
        }

        // Setting HTTP headers
        Engine.logEngine.debug("(HttpClient) Incoming HTTP headers:");
        String headerName, headerValue;
        for (int k = 0, kSize = infoShuttle.userHeaderNames.size(); k < kSize; k++) {
            headerName = (String) infoShuttle.userHeaderNames.get(k);
            // Cookies are handled by HttpClient, so we do not have to proxy Cookie header
            // See #986 (Multiples cookies don't work with some proxies)
            if (headerName.toLowerCase().equals("cookie")) {
                Engine.logEngine.debug("Cookie header ignored");
            } else {
                headerValue = (String) infoShuttle.userHeaderValues.get(k);
                method.setRequestHeader(headerName, headerValue);
                Engine.logEngine.debug(headerName + "=" + headerValue);
            }
        }

        // Getting the result
        executeMethod(method, connector, resourceUrl, infoShuttle);
        result = method.getResponseBody();

    } finally {
        if (method != null)
            method.releaseConnection();
    }

    return result;
}

From source file:net.jadler.JadlerStubbingIntegrationTest.java

@Test
public void havingParameterPOST() throws Exception {
    final String body = "p1=p1v1&p2=p2v1&p2=p2v2&p3=&p4";

    onRequest().havingParameter("p1").havingParameter("p1", hasSize(1))
            .havingParameter("p1", everyItem(not(isEmptyOrNullString())))
            .havingParameter("p1", contains("p1v1")).havingParameterEqualTo("p1", "p1v1").havingParameter("p2")
            .havingParameter("p2", hasSize(3)).havingParameter("p2", hasItems("p2v1", "p2v2", "p2v3"))
            .havingParameterEqualTo("p2", "p2v1").havingParameterEqualTo("p2", "p2v2")
            .havingParameterEqualTo("p2", "p2v3").havingParameters("p1", "p2").havingParameter("p3")
            .havingParameter("p3", contains("")).havingParameterEqualTo("p3", "").havingParameter("p4")
            .havingParameter("p4", contains("")).havingParameterEqualTo("p4", "")
            .havingParameter("p5", nullValue()).havingBodyEqualTo(body).respond().withStatus(201);

    final PostMethod method = new PostMethod("http://localhost:" + port() + "?p2=p2v3");
    method.setRequestEntity(new StringRequestEntity(body, "application/x-www-form-urlencoded", "UTF-8"));

    int status = client.executeMethod(method);
    assertThat(status, is(201));//from  ww  w .  j  a  va 2s  .c o m
}

From source file:com.cloudbees.api.BeesClient.java

/**
 * Sends a request in JSON and expects a JSON response back.
 *
 * @param urlTail The end point to hit. Appended to {@link #base}. Shouldn't start with '/'
 * @param method  HTTP method name like GET or POST.
 * @param headers//from ww w . ja  v  a  2s.  com
 *@param jsonContent  The json request payload, or null if none.  @throws IOException If the communication fails.
 */
public HttpReply jsonRequest(String urlTail, String method, Map<String, String> headers, String jsonContent)
        throws IOException {
    HttpMethodBase httpMethod;

    String urlString = absolutize(urlTail);

    trace("API call: " + urlString);
    if (method.equalsIgnoreCase("GET")) {
        httpMethod = new GetMethod(urlString);
    } else if ((method.equalsIgnoreCase("POST"))) {
        httpMethod = new PostMethod(urlString);
    } else if ((method.equalsIgnoreCase("PUT"))) {
        httpMethod = new PutMethod(urlString);
    } else if ((method.equalsIgnoreCase("DELETE"))) {
        httpMethod = new DeleteMethod(urlString);
    } else if ((method.equalsIgnoreCase("PATCH"))) {
        httpMethod = new PatchMethod(urlString);
    } else if ((method.equalsIgnoreCase("HEAD"))) {
        httpMethod = new HeadMethod(urlString);
    } else if ((method.equalsIgnoreCase("TRACE"))) {
        httpMethod = new TraceMethod(urlString);
    } else if ((method.equalsIgnoreCase("OPTIONS"))) {
        httpMethod = new OptionsMethod(urlString);
    } else
        throw new IOException("Method not supported: " + method);

    httpMethod.setRequestHeader("Accept", "application/json");
    if (jsonContent != null && httpMethod instanceof EntityEnclosingMethod) {
        StringRequestEntity requestEntity = new StringRequestEntity(jsonContent, "application/json", "UTF-8");
        ((EntityEnclosingMethod) httpMethod).setRequestEntity(requestEntity);
        trace("Payload: " + jsonContent);
    }

    return executeRequest(httpMethod, headers);
}

From source file:au.edu.usq.fascinator.harvester.fedora.restclient.FedoraRestClient.java

public void addExternalDatastream(String pid, String dsId, String dsLabel, String contentType,
        String dsLocation) throws IOException {
    Properties options = new Properties();
    options.setProperty("dsLabel", dsLabel);
    options.setProperty("controlGroup", "E");
    options.setProperty("dsLocation", dsLocation);
    RequestEntity request = new StringRequestEntity("", contentType, "UTF-8");
    addDatastream(pid, dsId, options, contentType, request);
}

From source file:com.ning.http.client.providers.apache.ApacheAsyncHttpProvider.java

private HttpMethodBase createMethod(HttpClient client, Request request)
        throws IOException, FileNotFoundException {
    String methodName = request.getMethod();
    HttpMethodBase method = null;//from   w ww. ja  va2 s .c  om
    if (methodName.equalsIgnoreCase("POST") || methodName.equalsIgnoreCase("PUT")) {
        EntityEnclosingMethod post = methodName.equalsIgnoreCase("POST") ? new PostMethod(request.getUrl())
                : new PutMethod(request.getUrl());

        String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding();

        post.getParams().setContentCharset("ISO-8859-1");
        if (request.getByteData() != null) {
            post.setRequestEntity(new ByteArrayRequestEntity(request.getByteData()));
            post.setRequestHeader("Content-Length", String.valueOf(request.getByteData().length));
        } else if (request.getStringData() != null) {
            post.setRequestEntity(new StringRequestEntity(request.getStringData(), "text/xml", bodyCharset));
            post.setRequestHeader("Content-Length",
                    String.valueOf(request.getStringData().getBytes(bodyCharset).length));
        } else if (request.getStreamData() != null) {
            InputStreamRequestEntity r = new InputStreamRequestEntity(request.getStreamData());
            post.setRequestEntity(r);
            post.setRequestHeader("Content-Length", String.valueOf(r.getContentLength()));

        } else if (request.getParams() != null) {
            StringBuilder sb = new StringBuilder();
            for (final Map.Entry<String, List<String>> paramEntry : request.getParams()) {
                final String key = paramEntry.getKey();
                for (final String value : paramEntry.getValue()) {
                    if (sb.length() > 0) {
                        sb.append("&");
                    }
                    UTF8UrlEncoder.appendEncoded(sb, key);
                    sb.append("=");
                    UTF8UrlEncoder.appendEncoded(sb, value);
                }
            }

            post.setRequestHeader("Content-Length", String.valueOf(sb.length()));
            post.setRequestEntity(new StringRequestEntity(sb.toString(), "text/xml", "ISO-8859-1"));

            if (!request.getHeaders().containsKey("Content-Type")) {
                post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            }
        } else if (request.getParts() != null) {
            MultipartRequestEntity mre = createMultipartRequestEntity(bodyCharset, request.getParts(),
                    post.getParams());
            post.setRequestEntity(mre);
            post.setRequestHeader("Content-Type", mre.getContentType());
            post.setRequestHeader("Content-Length", String.valueOf(mre.getContentLength()));
        } else if (request.getEntityWriter() != null) {
            post.setRequestEntity(new EntityWriterRequestEntity(request.getEntityWriter(),
                    computeAndSetContentLength(request, post)));
        } else if (request.getFile() != null) {
            File file = request.getFile();
            if (!file.isFile()) {
                throw new IOException(
                        String.format(Thread.currentThread() + "File %s is not a file or doesn't exist",
                                file.getAbsolutePath()));
            }
            post.setRequestHeader("Content-Length", String.valueOf(file.length()));

            FileInputStream fis = new FileInputStream(file);
            try {
                InputStreamRequestEntity r = new InputStreamRequestEntity(fis);
                post.setRequestEntity(r);
                post.setRequestHeader("Content-Length", String.valueOf(r.getContentLength()));
            } finally {
                fis.close();
            }
        } else if (request.getBodyGenerator() != null) {
            Body body = request.getBodyGenerator().createBody();
            try {
                int length = (int) body.getContentLength();
                if (length < 0) {
                    length = (int) request.getContentLength();
                }

                // TODO: This is suboptimal
                if (length >= 0) {
                    post.setRequestHeader("Content-Length", String.valueOf(length));

                    // This is totally sub optimal
                    byte[] bytes = new byte[length];
                    ByteBuffer buffer = ByteBuffer.wrap(bytes);
                    for (;;) {
                        buffer.clear();
                        if (body.read(buffer) < 0) {
                            break;
                        }
                    }
                    post.setRequestEntity(new ByteArrayRequestEntity(bytes));
                }
            } finally {
                try {
                    body.close();
                } catch (IOException e) {
                    logger.warn("Failed to close request body: {}", e.getMessage(), e);
                }
            }
        }

        if (request.getHeaders().getFirstValue("Expect") != null
                && request.getHeaders().getFirstValue("Expect").equalsIgnoreCase("100-Continue")) {
            post.setUseExpectHeader(true);
        }
        method = post;
    } else if (methodName.equalsIgnoreCase("DELETE")) {
        method = new DeleteMethod(request.getUrl());
    } else if (methodName.equalsIgnoreCase("HEAD")) {
        method = new HeadMethod(request.getUrl());
    } else if (methodName.equalsIgnoreCase("GET")) {
        method = new GetMethod(request.getUrl());
    } else if (methodName.equalsIgnoreCase("OPTIONS")) {
        method = new OptionsMethod(request.getUrl());
    } else {
        throw new IllegalStateException(String.format("Invalid Method", methodName));
    }

    ProxyServer proxyServer = request.getProxyServer() != null ? request.getProxyServer()
            : config.getProxyServer();
    boolean avoidProxy = ProxyUtils.avoidProxy(proxyServer, request);
    if (!avoidProxy) {

        if (proxyServer.getPrincipal() != null) {
            Credentials defaultcreds = new UsernamePasswordCredentials(proxyServer.getPrincipal(),
                    proxyServer.getPassword());
            client.getState().setCredentials(new AuthScope(null, -1, AuthScope.ANY_REALM), defaultcreds);
        }

        ProxyHost proxyHost = proxyServer == null ? null
                : new ProxyHost(proxyServer.getHost(), proxyServer.getPort());
        client.getHostConfiguration().setProxyHost(proxyHost);
    }

    method.setFollowRedirects(false);
    if ((request.getCookies() != null) && !request.getCookies().isEmpty()) {
        for (Cookie cookie : request.getCookies()) {
            method.setRequestHeader("Cookie", AsyncHttpProviderUtils.encodeCookies(request.getCookies()));
        }
    }

    if (request.getHeaders() != null) {
        for (String name : request.getHeaders().keySet()) {
            if (!"host".equalsIgnoreCase(name)) {
                for (String value : request.getHeaders().get(name)) {
                    method.setRequestHeader(name, value);
                }
            }
        }
    }

    if (request.getHeaders().getFirstValue("User-Agent") != null) {
        method.setRequestHeader("User-Agent", request.getHeaders().getFirstValue("User-Agent"));
    } else if (config.getUserAgent() != null) {
        method.setRequestHeader("User-Agent", config.getUserAgent());
    } else {
        method.setRequestHeader("User-Agent",
                AsyncHttpProviderUtils.constructUserAgent(ApacheAsyncHttpProvider.class));
    }

    if (config.isCompressionEnabled()) {
        Header acceptableEncodingHeader = method.getRequestHeader("Accept-Encoding");
        if (acceptableEncodingHeader != null) {
            String acceptableEncodings = acceptableEncodingHeader.getValue();
            if (acceptableEncodings.indexOf("gzip") == -1) {
                StringBuilder buf = new StringBuilder(acceptableEncodings);
                if (buf.length() > 1) {
                    buf.append(",");
                }
                buf.append("gzip");
                method.setRequestHeader("Accept-Encoding", buf.toString());
            }
        } else {
            method.setRequestHeader("Accept-Encoding", "gzip");
        }
    }

    if (request.getVirtualHost() != null) {

        String vs = request.getVirtualHost();
        int index = vs.indexOf(":");
        if (index > 0) {
            vs = vs.substring(0, index);
        }
        method.getParams().setVirtualHost(vs);
    }

    return method;
}

From source file:com.kylinolap.jdbc.stub.KylinClient.java

/**
 * @param sql// w  w w . ja va 2s . c  om
 * @return
 * @throws IOException
 */
private SQLResponseStub runKylinQuery(String sql, List<StateParam> params) throws SQLException {
    String url = conn.getQueryUrl();
    String project = conn.getProject();
    QueryRequest request = null;

    if (null != params) {
        request = new PreQueryRequest();
        ((PreQueryRequest) request).setParams(params);
        url += "/prestate";
    } else {
        request = new QueryRequest();
    }
    request.setSql(sql);
    request.setProject(project);

    PostMethod post = new PostMethod(url);
    addPostHeaders(post);
    HttpClient httpClient = new HttpClient();
    if (conn.getQueryUrl().toLowerCase().startsWith("https://")) {
        registerSsl();
    }

    String postBody = null;
    ObjectMapper mapper = new ObjectMapper();
    try {
        postBody = mapper.writeValueAsString(request);
        logger.debug("Post body:\n " + postBody);
    } catch (JsonProcessingException e) {
        logger.error(e.getLocalizedMessage(), e);
    }
    String response = null;
    SQLResponseStub queryRes = null;

    try {
        StringRequestEntity requestEntity = new StringRequestEntity(postBody, "application/json", "UTF-8");
        post.setRequestEntity(requestEntity);

        httpClient.executeMethod(post);
        response = post.getResponseBodyAsString();

        if (post.getStatusCode() != 200 && post.getStatusCode() != 201) {
            logger.error("Failed to query", response);
            throw new SQLException(response);
        }

        queryRes = new ObjectMapper().readValue(response, SQLResponseStub.class);

    } catch (HttpException e) {
        logger.error(e.getLocalizedMessage(), e);
        throw new SQLException(e.getLocalizedMessage());
    } catch (IOException e) {
        logger.error(e.getLocalizedMessage(), e);
        throw new SQLException(e.getLocalizedMessage());
    }

    return queryRes;
}

From source file:com.cubeia.backoffice.wallet.client.WalletServiceClientHTTP.java

@Override
public void transfer(Long accountId, TransferRequest request) {
    String resource = String.format(baseUrl + ACCOUNT, accountId);
    PostMethod method = new PostMethod(resource);
    try {//from  ww w  .ja  v  a  2 s .c om
        String data = serialize(request);
        if (log.isTraceEnabled()) {
            log.trace("Transfer JSON data: " + data);
        }
        method.setRequestEntity(new StringRequestEntity(data, MIME_TYPE_JSON, DEFAULT_CHAR_ENCODING));
        // Execute the HTTP Call
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return;
        }
        assertResponseCodeOK(method, statusCode);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        method.releaseConnection();
    }
}

From source file:eu.learnpad.core.impl.or.XwikiBridgeInterfaceRestResource.java

@Override
public Entities analyseText(String modelSetId, String contextArtifactId, String userId, String title,
        String text) throws LpRestException {
    HttpClient httpClient = this.getClient();
    String uri = String.format("%s/learnpad/or/bridge/%s/analysetext", DefaultRestResource.REST_URI,
            modelSetId);//from w  ww. j  a v  a  2 s. co m
    PostMethod postMethod = new PostMethod(uri);
    postMethod.addRequestHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML);

    NameValuePair[] queryString = new NameValuePair[4];
    queryString[0] = new NameValuePair("modelsetid", modelSetId);
    queryString[1] = new NameValuePair("contextArtifactId", contextArtifactId);
    queryString[2] = new NameValuePair("userid", userId);
    queryString[3] = new NameValuePair("title", title);
    postMethod.setQueryString(queryString);

    RequestEntity requestEntity;
    InputStream entitiesAsStream = null;
    try {
        requestEntity = new StringRequestEntity(text, MediaType.APPLICATION_XML, "UTF-8");
        postMethod.setRequestEntity(requestEntity);

        httpClient.executeMethod(postMethod);
        entitiesAsStream = postMethod.getResponseBodyAsStream();
    } catch (IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause());
    }

    Entities entities = null;

    try {
        JAXBContext jc = JAXBContext.newInstance(Entities.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        entities = (Entities) unmarshaller.unmarshal(entitiesAsStream);
    } catch (JAXBException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause());
    }
    return entities;
}

From source file:com.evolveum.midpoint.model.impl.bulkmodify.PostXML.java

public String searchRolesByNamePostMethod(String roleName) throws Exception {
    String returnOid = "";

    // Get target URL
    String strURL = "http://localhost:8080/midpoint/ws/rest/roles/search";

    // Prepare HTTP post
    PostMethod post = new PostMethod(strURL);

    //AUTHENTICATION BY GURER
    //String username = "administrator";
    //String password = "5ecr3t";
    String userPass = this.getUsername() + ":" + this.getPassword();
    String basicAuth = "Basic "
            + javax.xml.bind.DatatypeConverter.printBase64Binary(userPass.getBytes("UTF-8"));
    post.addRequestHeader("Authorization", basicAuth);

    //construct searching string. place "name" attribute into <values> tags.
    String sendingXml = XML_TEMPLATE_SEARCH_IGNORECASE;

    sendingXml = sendingXml.replace("<value></value>", "<value>" + roleName + "</value>");

    RequestEntity userSearchEntity = new StringRequestEntity(sendingXml, "application/xml", "UTF-8");
    post.setRequestEntity(userSearchEntity);
    // Get HTTP client
    HttpClient httpclient = new HttpClient();
    // Execute request
    try {// w ww .ja  v  a2s.  c  o  m
        int result = httpclient.executeMethod(post);
        // Display status code
        //System.out.println("Response status code: " + result);
        // Display response
        //System.out.println("Response body: ");
        // System.out.println(post.getResponseBodyAsString());
        String sbf = new String(post.getResponseBodyAsString());
        //System.out.println(sbf);

        //find oid
        if (sbf.contains("oid")) {
            int begin = sbf.indexOf("oid");
            returnOid = (sbf.substring(begin + 5, begin + 41));
        }

    } finally {
        // Release current connection to the connection pool once you are done
        post.releaseConnection();
    }

    return returnOid;
}