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

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

Introduction

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

Prototype

public ByteArrayRequestEntity(byte[] paramArrayOfByte) 

Source Link

Usage

From source file:net.jadler.AbstractJadlerStubbingIntegrationTest.java

@Test
public void havingRawBody() throws IOException {
    onRequest().havingRawBodyEqualTo(BINARY_BODY).respond().withStatus(201);

    final PostMethod method = new PostMethod("http://localhost:" + port());
    method.setRequestEntity(new ByteArrayRequestEntity(BINARY_BODY));

    final int status = client.executeMethod(method);
    assertThat(status, is(201));/*from w  ww  .  ja v a2s. c  o  m*/

    method.releaseConnection();
}

From source file:com.ibm.hrl.proton.adapters.rest.client.RestClient.java

protected static void patchEventToConsumer(String url, String urlExtension, String eventInstance,
        String contentType, String authToken) throws RESTException {
    // Prepare HTTP PUT
    String consumer = url + "/" + urlExtension;

    PostMethod postMethod = new PostMethod(consumer) {
        @Override// w w w. j a  va 2s.c  o  m
        public String getName() {
            return "PATCH";
        }
    };

    if (eventInstance != null) {

        RequestEntity requestEntity = new ByteArrayRequestEntity(eventInstance.getBytes());
        postMethod.setRequestEntity(requestEntity);

        // Specify content type and encoding
        // If content encoding is not explicitly specified
        // ISO-8859-1 is assumed
        // postMethod.setRequestHeader("Content-Type", contentType+"; charset=ISO-8859-1");
        postMethod.setRequestHeader("Content-Type", contentType);

        if (null != authToken && !authToken.isEmpty()) {
            postMethod.setRequestHeader("X-Auth-Token", authToken);
        }

        // Get HTTP client
        HttpClient httpclient = new HttpClient();

        // Execute request
        try {

            int result = httpclient.executeMethod(postMethod);

            if (result < 200 || result >= 300) {
                Header[] reqHeaders = postMethod.getRequestHeaders();
                StringBuffer headers = new StringBuffer();
                for (int i = 0; i < reqHeaders.length; i++) {
                    headers.append(reqHeaders[i].toString());
                    headers.append("\n");
                }
                throw new RESTException("Could not perform PATCH of event instance: \n" + eventInstance
                        + "\nwith request headers:\n" + headers + "to consumer " + consumer
                        + ", responce result: " + result);
            }

        } catch (Exception e) {
            throw new RESTException(e);
        } finally {
            // Release current connection to the connection pool 
            // once you are done
            postMethod.releaseConnection();
        }
    } else {
        System.out.println("Invalid request");
    }
    //        PutMethod putMethod = new PutMethod(url);        
    // 
    //        if(eventInstance != null) {
    //           RequestEntity requestEntity = new ByteArrayRequestEntity(eventInstance.getBytes());
    //           putMethod.setRequestEntity(requestEntity);
    //
    //        
    //           // Specify content type and encoding
    //           // If content encoding is not explicitly specified
    //           // ISO-8859-1 is assumed
    //           putMethod.setRequestHeader(
    //                   "Content-type", contentType+"; charset=ISO-8859-1");
    //           
    //           // Get HTTP client
    //           HttpClient httpclient = new HttpClient();
    //           
    //           // Execute request
    //           try {
    //               
    //               int result = httpclient.executeMethod(putMethod);
    //                              
    //               if (result < 200 || result >= 300)
    //               {
    //                  throw new RESTException("Could not perform PUT of event instance "+eventInstance+" to consumer "+ url+", responce result: "+result);
    //               }
    //              
    //           } catch(Exception e)
    //           {
    //              throw new RESTException(e);
    //           }
    //           finally {
    //               // Release current connection to the connection pool 
    //               // once you are done
    //               putMethod.releaseConnection();
    //           }
    //        } else
    //        {
    //           System.out.println ("Invalid request");
    //        }

}

From source file:net.sf.dsig.verify.OCSPHelper.java

/**
 * Check with OCSP protocol whether a certificate is valid
 * //from www. j a  v a2  s  . c om
 * @param certificate an {@link X509Certificate} object
 * @return true if the certificate is valid; false otherwise
 * @throws NetworkAccessException when any network access issues occur
 * @throws VerificationException when an OCSP related error occurs
 */
public boolean isValid(X509Certificate certificate) throws NetworkAccessException, VerificationException {
    PostMethod post = null;

    try {
        CertificateID cid = new CertificateID(CertificateID.HASH_SHA1, caCertificate,
                certificate.getSerialNumber());

        OCSPReqGenerator gen = new OCSPReqGenerator();
        gen.addRequest(cid);

        // Nonce
        BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
        Vector oids = new Vector();
        Vector values = new Vector();
        oids.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
        values.add(new X509Extension(false, new DEROctetString(nonce.toByteArray())));
        values.add(new X509Extension(false,
                new DEROctetString(new BigInteger("041063FAB2B54CF1ED014F9DF7C70AACE575", 16).toByteArray())));
        gen.setRequestExtensions(new X509Extensions(oids, values));

        // Requestor name - not really required, but added for completeness
        //          gen.setRequestorName(
        //                  new GeneralName(
        //                          new X509Name(
        //                                  certificate.getSubjectX500Principal().getName())));

        logger.debug("Generating OCSP request" + "; serialNumber=" + certificate.getSerialNumber().toString(16)
                + ", nonce=" + nonce.toString(16) + ", caCertificate.subjectName="
                + caCertificate.getSubjectX500Principal().getName());

        // TODO Need to call the generate(...) method, that signs the 
        // request. Which means, need to have a keypair for that, too
        OCSPReq req = gen.generate();

        // First try finding the OCSP access location in the X.509 certificate
        String uriAsString = getOCSPAccessLocationUri(certificate);

        // If not found, try falling back to the default
        if (uriAsString == null) {
            uriAsString = defaultOcspAccessLocation;
        }

        // If still null, bail out
        if (uriAsString == null) {
            throw new ConfigurationException(
                    "OCSP AccessLocation not found on certificate, and no default set");
        }

        HostConfiguration config = getHostConfiguration();

        post = new PostMethod(uriAsString);
        post.setRequestHeader("Content-Type", "application/ocsp-request");
        post.setRequestHeader("Accept", "application/ocsp-response");
        post.setRequestEntity(new ByteArrayRequestEntity(req.getEncoded()));

        getHttpClient().executeMethod(config, post);

        logger.debug("HTTP POST executed" + "; authorityInfoAccessUri=" + uriAsString + ", statusLine="
                + post.getStatusLine());

        if (post.getStatusCode() != HttpStatus.SC_OK) {
            throw new NetworkAccessException("HTTP GET failed; statusLine=" + post.getStatusLine());
        }

        byte[] responseBodyBytes = post.getResponseBody();

        OCSPResp ocspRes = new OCSPResp(responseBodyBytes);
        if (ocspRes.getStatus() != OCSPResponseStatus.SUCCESSFUL) {
            // One possible exception is the use of a wrong CA certificate
            throw new ConfigurationException("OCSP request failed; possibly wrong issuer/user certificate"
                    + "; status=" + ocspRes.getStatus());
        }

        BasicOCSPResp res = (BasicOCSPResp) ocspRes.getResponseObject();
        SingleResp[] responses = res.getResponses();
        SingleResp response = responses[0];

        CertificateStatus status = (CertificateStatus) response.getCertStatus();
        // Normal OCSP protocol allows a null status
        return status == null || status == CertificateStatus.GOOD;
    } catch (IOException e) {
        throw new NetworkAccessException("I/O error occured", e);
    } catch (OCSPException e) {
        throw new VerificationException("Error while following OCSP protocol", e);
    } finally {
        if (post != null) {
            post.releaseConnection();
        }
    }
}

From source file:com.wandisco.s3hdfs.rewrite.redirect.VersionRedirect.java

/**
 * Places a new .v file in the default version directory.
 *
 * @param nnHostAddress//from w  ww .  j a  v a2s.com
 * @param userName
 * @throws IOException
 */
public String createVersion(String nnHostAddress, String userName) throws IOException {
    String[] nnHost = nnHostAddress.split(":");

    String uri = (path != null) ? path.getFullHdfsObjPath() : request.getPathInfo();

    String versionpath = replaceUri(uri, OBJECT_FILE_NAME, VERSION_FILE_NAME);

    PutMethod httpPut = (PutMethod) getHttpMethod(request.getScheme(), nnHost[0], Integer.decode(nnHost[1]),
            "CREATE&overwrite=true", userName, versionpath, PUT);
    String version = UUID.randomUUID().toString();
    httpPut.setRequestEntity(new ByteArrayRequestEntity(version.getBytes(DEFAULT_CHARSET)));

    httpPut.setRequestHeader(S3_HEADER_NAME, S3_HEADER_VALUE);

    httpClient.executeMethod(httpPut);

    Header locationHeader = httpPut.getResponseHeader("Location");
    LOG.debug("1st response: " + httpPut.getStatusLine().toString());
    boolean containsRedirect = (locationHeader != null);
    httpPut.releaseConnection();

    if (!containsRedirect) {
        LOG.debug("1st response did not contain redirect. " + "No version will be created.");
        return null;
    }

    // Handle redirect header transition
    assert httpPut.getStatusCode() == 307;

    // Consume response and re-allocate connection for redirect
    httpPut.setURI(new URI(locationHeader.getValue(), true));

    httpClient.executeMethod(httpPut);

    LOG.debug("2nd response: " + httpPut.getStatusLine().toString());

    if (httpPut.getStatusCode() != 200) {
        LOG.debug("Response not 200: " + httpPut.getResponseBodyAsString());
        return null;
    }

    assert httpPut.getStatusCode() == 200;
    httpPut.releaseConnection();

    return version;
}

From source file:com.google.apphosting.vmruntime.jetty9.VmRuntimeJettyKitchenSink2Test.java

/**
 * Test that the deferredTask handler is installed.
 *//*from   w ww  .j a  va 2s  . com*/
public void testDeferredTask() throws Exception {
    // Replace the API proxy delegate so we can fake API responses.
    FakeableVmApiProxyDelegate fakeApiProxy = new FakeableVmApiProxyDelegate();
    ApiProxy.setDelegate(fakeApiProxy);

    // Add a api response so the task queue api is happy.
    TaskQueueBulkAddResponse taskAddResponse = new TaskQueueBulkAddResponse();
    TaskResult taskResult = taskAddResponse.addTaskResult();
    taskResult.setResult(ErrorCode.OK.getValue());
    taskResult.setChosenTaskName("abc");
    fakeApiProxy.addApiResponse(taskAddResponse);

    // Issue a deferredTaskRequest with payload.
    String testData = "0987654321acbdefghijklmn";
    String[] lines = fetchUrl(createUrl("/testTaskQueue?deferredTask=1&deferredData=" + testData));
    TaskQueueBulkAddRequest request = new TaskQueueBulkAddRequest();
    request.parseFrom(fakeApiProxy.getLastRequest().requestData);
    assertEquals(1, request.addRequestSize());
    TaskQueueAddRequest addRequest = request.getAddRequest(0);
    assertEquals(TaskQueueAddRequest.RequestMethod.POST.getValue(), addRequest.getMethod());

    // Pull out the request and fire it at the app.
    HttpClient httpClient = new HttpClient();
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
    PostMethod post = new PostMethod(createUrl(addRequest.getUrl()).toString());
    post.getParams().setVersion(HttpVersion.HTTP_1_0);
    // Add the required Task queue header, plus any headers from the request.
    post.addRequestHeader("X-AppEngine-QueueName", "1");
    for (TaskQueueAddRequest.Header header : addRequest.headers()) {
        post.addRequestHeader(header.getKey(), header.getValue());
    }
    post.setRequestEntity(new ByteArrayRequestEntity(addRequest.getBodyAsBytes()));
    int httpCode = httpClient.executeMethod(post);
    assertEquals(HttpURLConnection.HTTP_OK, httpCode);

    // Verify that the task was handled and that the payload is correct.
    lines = fetchUrl(createUrl("/testTaskQueue?getLastPost=1"));
    assertEquals("deferredData:" + testData, lines[lines.length - 1]);
}

From source file:com.silverpeas.openoffice.windows.webdav.WebdavManager.java

/**
 * Update a ressource on the webdav file server.
 *
 * @param uri the uri to the ressource.//from w  w  w.  j  a  va 2s. c  o  m
 * @param localFilePath the path to the file to be uploaded on the filesystem.
 * @param lockToken the current lock token.
 * @throws IOException
 */
public void putFile(URI uri, String localFilePath, String lockToken) throws IOException {
    // Checks if file still exists
    try {
        executeGetFile(uri);
    } catch (IOException ioex) {
        logger.log(Level.SEVERE, MessageUtil.getMessage("error.remote.file"));
        throw new IOException(MessageUtil.getMessage("error.remote.file"));
    }
    PutMethod putMethod = new PutMethod(uri.getEscapedURI());
    logger.log(Level.INFO, "{0} {1}",
            new Object[] { MessageUtil.getMessage("info.webdav.put"), localFilePath });
    File file = new File(localFilePath);
    UploadProgressBar progress = new UploadProgressBar();
    progress.setMaximum(new Long(file.length()).intValue());
    progress.setMessage(MessageUtil.getMessage("uploading.remote.file") + ' '
            + uri.getPath().substring(uri.getPath().lastIndexOf('/') + 1));
    MonitoredInputStream is = new MonitoredInputStream(new BufferedInputStream(new FileInputStream(file)));
    is.addPropertyChangeListener(progress);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] data = new byte[64];
    int c = 0;
    while ((c = is.read(data)) > -1) {
        baos.write(data, 0, c);
    }
    RequestEntity requestEntity = new ByteArrayRequestEntity(baos.toByteArray());
    putMethod.setRequestEntity(requestEntity);
    putMethod.setRequestHeader(PutMethod.HEADER_LOCK_TOKEN, lockToken);
    client.executeMethod(putMethod);
    progress.close();
    if (putMethod.succeeded()) {
        logger.log(Level.INFO, MessageUtil.getMessage("info.file.updated"));
    } else {
        throw new IOException(MessageUtil.getMessage("error.put.remote.file") + " - "
                + putMethod.getStatusCode() + " - " + putMethod.getStatusText());
    }
}

From source file:lucee.commons.net.http.httpclient3.HTTPEngine3Impl.java

private static RequestEntity toRequestEntity(Object value) throws PageException {
    if (value instanceof RequestEntity)
        return (RequestEntity) value;

    else if (value instanceof InputStream) {
        return new InputStreamRequestEntity((InputStream) value, "application/octet-stream");
    } else if (Decision.isCastableToBinary(value, false)) {
        return new ByteArrayRequestEntity(Caster.toBinary(value));
    } else {/*from  w w  w . ja v  a 2s  . com*/
        return new StringRequestEntity(Caster.toString(value));
    }
}

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 w w .ja va 2s . c o m*/
    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.ning.http.client.providers.apache.TestableApacheAsyncHttpProvider.java

/**
 * This one we can get into//from   w w w .  jav a2 s . c  o m
 */
protected HttpMethodBase getHttpMethodBase(HttpClient client, Request request) throws IOException {
    String methodName = request.getMethod();
    HttpMethodBase method;
    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()));

            try (FileInputStream fis = new FileInputStream(file)) {
                InputStreamRequestEntity r = new InputStreamRequestEntity(fis);
                post.setRequestEntity(r);
                post.setRequestHeader("Content-Length", String.valueOf(r.getContentLength()));
            }
        } 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 {
        method = testMethodFactory.createMethod(methodName, request);
    }

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

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

        ProxyHost proxyHost = proxyServer == null ? null
                : new ProxyHost(proxyServer.getHost(), proxyServer.getPort());
        client.getHostConfiguration().setProxyHost(proxyHost);
    }
    if (request.getLocalAddress() != null) {
        client.getHostConfiguration().setLocalAddress(request.getLocalAddress());
    }

    method.setFollowRedirects(false);
    if (isNonEmpty(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(TestableApacheAsyncHttpProvider.class));
    }

    if (config.isCompressionEnabled()) {
        Header acceptableEncodingHeader = method.getRequestHeader("Accept-Encoding");
        if (acceptableEncodingHeader != null) {
            String acceptableEncodings = acceptableEncodingHeader.getValue();
            if (!acceptableEncodings.contains("gzip")) {
                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.panet.imeta.cluster.SlaveServer.java

public String sendXML(String xml, String service) throws Exception {
    // The content
    // //from  w w  w.  j a v a2s .c  o m
    byte[] content = xml.getBytes(Const.XML_ENCODING);

    // Prepare HTTP put
    // 
    String urlString = constructUrl(service);
    log.logDebug(toString(), Messages.getString("SlaveServer.DEBUG_ConnectingTo", urlString)); //$NON-NLS-1$
    PutMethod put = new PutMethod(urlString);

    // Request content will be retrieved directly from the input stream
    // 
    RequestEntity entity = new ByteArrayRequestEntity(content);

    put.setRequestEntity(entity);
    put.setDoAuthentication(true);
    put.addRequestHeader(new Header("Content-Type", "text/xml;charset=" + Const.XML_ENCODING));

    // post.setContentChunked(true);

    // Get HTTP client
    // 
    HttpClient client = new HttpClient();
    addCredentials(client);

    // Execute request
    // 
    try {
        int result = client.executeMethod(put);

        // The status code
        log.logDebug(toString(),
                Messages.getString("SlaveServer.DEBUG_ResponseStatus", Integer.toString(result))); //$NON-NLS-1$

        // the response
        InputStream inputStream = new BufferedInputStream(put.getResponseBodyAsStream(), 1000);

        StringBuffer bodyBuffer = new StringBuffer();
        int c;
        while ((c = inputStream.read()) != -1)
            bodyBuffer.append((char) c);
        inputStream.close();
        String bodyTmp = bodyBuffer.toString();

        switch (result) {
        case 401: // Security problem: authentication required
            // Non-internationalized message
            String message = "Authentication failed" + Const.DOSCR + Const.DOSCR + bodyTmp; //$NON-NLS-1$
            WebResult webResult = new WebResult(WebResult.STRING_ERROR, message);
            bodyBuffer.setLength(0);
            bodyBuffer.append(webResult.getXML());
            break;
        }

        String body = bodyBuffer.toString();

        // String body = post.getResponseBodyAsString(); 
        log.logDebug(toString(), Messages.getString("SlaveServer.DEBUG_ResponseBody", body)); //$NON-NLS-1$

        return body;
    } finally {
        // Release current connection to the connection pool once you are done
        put.releaseConnection();
        log.logDetailed(toString(),
                Messages.getString("SlaveServer.DETAILED_SentXmlToService", service, hostname)); //$NON-NLS-1$
    }
}