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

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

Introduction

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

Prototype

public void setContentChunked(boolean paramBoolean) 

Source Link

Usage

From source file:ChunkEncodedPost.java

public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.out.println("Usage: ChunkEncodedPost <file>");
        System.out.println("<file> - full path to a file to be posted");
        System.exit(1);//from www  .  j av a2  s  . c o  m
    }
    HttpClient client = new HttpClient();

    PostMethod httppost = new PostMethod("http://localhost:8080/httpclienttest/body");

    File file = new File(args[0]);

    httppost.setRequestEntity(new InputStreamRequestEntity(new FileInputStream(file)));
    httppost.setContentChunked(true);

    try {
        client.executeMethod(httppost);

        if (httppost.getStatusCode() == HttpStatus.SC_OK) {
            System.out.println(httppost.getResponseBodyAsString());
        } else {
            System.out.println("Unexpected failure: " + httppost.getStatusLine().toString());
        }
    } finally {
        httppost.releaseConnection();
    }
}

From source file:fedora.test.api.TestHTTPStatusCodes.java

private static int getUploadCode(FedoraClient client, String url, File file, String partName) throws Exception {
    PostMethod post = null;
    try {//from  w w  w  .j a  v a2  s . c  o m
        post = new PostMethod(url);
        post.setDoAuthentication(true);
        post.getParams().setParameter("Connection", "Keep-Alive");
        post.setContentChunked(true);
        Part[] parts = { new FilePart(partName, file) };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
        int responseCode = client.getHttpClient().executeMethod(post);
        if (responseCode > 299 && responseCode < 400) {
            String location = post.getResponseHeader("location").getValue();
            System.out.println("Redirected to " + location);
            return getUploadCode(client, location, file, partName);
        } else {
            return responseCode;
        }
    } finally {
        if (post != null) {
            post.releaseConnection();
        }
    }
}

From source file:de.juwimm.cms.common.http.Server2ServerAuthenticationStreamSupportingHttpInvokerRequestExecutor.java

protected PostMethod createPostMethodForStreaming(final HttpInvokerClientConfiguration config)
        throws IOException {
    HttpClientWrapper.getInstance().setHostConfiguration(super.getHttpClient(),
            new URL(config.getServiceUrl()));
    final PostMethod postMethod = new PostMethod(config.getServiceUrl());
    postMethod.setRequestHeader(HTTP_HEADER_CONTENT_TYPE, CONTENT_TYPE_SERIALIZED_OBJECT_WITH_STREAM);
    postMethod.setContentChunked(true);

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    if ((auth != null) && (auth.getName() != null) && (auth.getCredentials() != null)) {
        postMethod.setDoAuthentication(true);
        String base64 = auth.getName() + ":" + auth.getCredentials().toString();
        postMethod.addRequestHeader("Authorization",
                "Basic " + new String(Base64.encodeBase64(base64.getBytes())));

        if (log.isDebugEnabled()) {
            // log.debug("HttpInvocation now presenting via BASIC
            // authentication SecurityContextHolder-derived: " +
            // auth.toString());
            log.debug(//  w  ww  .j av  a 2s.c om
                    "HttpInvocation now presenting via BASIC authentication SecurityContextHolder-derived. User: "
                            + auth.getName());
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Unable to set BASIC authentication header as SecurityContext did not provide "
                    + "valid Authentication: " + auth);
        }
    }
    return postMethod;
}

From source file:edu.northwestern.jcr.adapter.fedora.persistence.FedoraConnectorREST.java

/**
 * Sends an HTTP POST request and returns the status code.
 *
 * @param url URL of the service/*from   w w w.ja v  a 2s  .co m*/
 * @return status code
 */
private int httpPost(String url) throws Exception {
    PostMethod postMethod = null;

    try {
        postMethod = new PostMethod(url);
        postMethod.setDoAuthentication(true);
        postMethod.getParams().setParameter("Connection", "Keep-Alive");
        postMethod.setContentChunked(true);
        fc.getHttpClient().executeMethod(postMethod);

        return postMethod.getStatusCode();
    } catch (Exception e) {
        String msg = "error connecting to the Fedora server";
        log.error(msg);
        throw new RepositoryException(msg, null);
    } finally {
        if (postMethod != null) {
            postMethod.releaseConnection();
        }
    }
}

From source file:com.bigdata.rdf.sail.remoting.GraphRepositoryClient.java

/**
 * @see {@link GraphRepository#create(String)}
 *//*from   www. ja  v a2 s  .  com*/
public void create(String rdfXml) throws Exception {

    // POST
    PostMethod post = new PostMethod(servletURL);
    try {

        // set the body
        if (rdfXml != null) {
            post.setRequestEntity(new StringRequestEntity(rdfXml, // the rdf/xml body
                    GraphRepositoryServlet.RDF_XML, // includes the encoding
                    null // so we don't need to say it here.
            ));
            post.setContentChunked(true);
        }

        // Execute the method.
        int sc = getHttpClient().executeMethod(post);
        if (sc != HttpStatus.SC_OK) {
            throw new IOException("HTTP-POST failed: " + post.getStatusLine());
        }

    } finally {
        // Release the connection.
        post.releaseConnection();
    }

}

From source file:com.aptana.jira.core.JiraManager.java

/**
 * Adds an attachment to a JIRA ticket.//w  w w  .  j a  va 2  s  .c  o m
 * 
 * @param path
 *            the path of the file to be attached
 * @param issue
 *            the JIRA ticket
 * @throws JiraException
 */
public void addAttachment(IPath path, JiraIssue issue) throws JiraException {
    if (path == null || issue == null) {
        return;
    }
    if (user == null) {
        throw new JiraException(Messages.JiraManager_ERR_NotLoggedIn);
    }

    // Use Apache HTTPClient to POST the file
    HttpClient httpclient = new HttpClient();
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user.getUsername(), user.getPassword());
    httpclient.getState().setCredentials(new AuthScope(HOST_NAME, 443), creds);
    httpclient.getParams().setAuthenticationPreemptive(true);
    PostMethod filePost = null;
    try {
        filePost = new PostMethod(createAttachmentURL(issue));
        File file = path.toFile();
        // MUST USE "file" AS THE NAME!!!
        Part[] parts = { new FilePart("file", file) }; //$NON-NLS-1$
        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
        filePost.setContentChunked(true);
        filePost.setDoAuthentication(true);
        // Special header to tell JIRA not to do XSFR checking
        filePost.setRequestHeader("X-Atlassian-Token", "nocheck"); //$NON-NLS-1$ //$NON-NLS-2$

        int responseCode = httpclient.executeMethod(filePost);
        if (responseCode != HttpURLConnection.HTTP_OK && responseCode != HttpURLConnection.HTTP_CREATED) {
            // TODO This is a JSON response that we should parse out "errorMessages" value(s) (its an array of
            // strings).
            throw new JiraException(filePost.getResponseBodyAsString());
        }
        String json = filePost.getResponseBodyAsString();
        IdeLog.logInfo(JiraCorePlugin.getDefault(), json);
    } catch (JiraException e) {
        throw e;
    } catch (Exception e) {
        throw new JiraException(e.getMessage(), e);
    } finally {
        if (filePost != null) {
            filePost.releaseConnection();
        }
    }
}

From source file:com.denimgroup.threadfix.cli.HttpRestUtils.java

public String httpPostFile(String request, File file, String[] paramNames, String[] paramVals) {

    Protocol.registerProtocol("https", new Protocol("https", new AcceptAllTrustFactory(), 443));

    PostMethod filePost = new PostMethod(request);

    filePost.setRequestHeader("Accept", "application/json");

    try {/*w ww .  j a v  a2  s  .  c om*/
        Part[] parts = new Part[paramNames.length + 1];
        parts[paramNames.length] = new FilePart("file", file);

        for (int i = 0; i < paramNames.length; i++) {
            parts[i] = new StringPart(paramNames[i], paramVals[i]);
        }

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

        filePost.setContentChunked(true);
        HttpClient client = new HttpClient();
        int status = client.executeMethod(filePost);
        if (status != 200) {
            System.err.println("Status was not 200.");
        }

        InputStream responseStream = filePost.getResponseBodyAsStream();

        if (responseStream != null) {
            return IOUtils.toString(responseStream);
        }

    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return "There was an error and the POST request was not finished.";
}

From source file:edu.northwestern.jcr.adapter.fedora.persistence.FedoraConnector.java

/**
 * Sends an HTTP POST request and returns the response body as
 * a string.//from   www  .j  a v a2  s.c o m
 *
 * @param url URL of the resource
 * @return the response body as <code>String</code>
 */
private String postMethod(String url) throws Exception {
    PostMethod postMethod;

    postMethod = new PostMethod(url);
    postMethod.setDoAuthentication(true);
    postMethod.getParams().setParameter("Connection", "Keep-Alive");
    postMethod.setContentChunked(true);
    try {
        fc.getHttpClient().executeMethod(postMethod);
    } catch (Exception e) {
        String msg = "error connecting to the Fedora server";
        log.error(msg);
        throw new RepositoryException(msg, null);
    }

    if (postMethod.getStatusCode() != SC_OK) {
        log.warn("status code: " + postMethod.getStatusCode());
    }

    return postMethod.getResponseBodyAsString();
}

From source file:com.denimgroup.threadfix.remote.HttpRestUtils.java

@Nonnull
public <T> RestResponse<T> httpPostFile(@Nonnull String path, @Nonnull File file, @Nonnull String[] paramNames,
        @Nonnull String[] paramVals, @Nonnull Class<T> targetClass) {

    if (isUnsafeFlag())
        Protocol.registerProtocol("https", new Protocol("https", new AcceptAllTrustFactory(), 443));

    String completeUrl = makePostUrl(path);
    if (completeUrl == null) {
        LOGGER.debug("The POST url could not be generated. Aborting request.");
        return ResponseParser
                .getErrorResponse("The POST url could not be generated and the request was not attempted.", 0);
    }/*from   w  w w .j ava  2 s  .com*/

    PostMethod filePost = new PostMethod(completeUrl);

    filePost.setRequestHeader("Accept", "application/json");

    RestResponse<T> response = null;
    int status = -1;

    try {
        Part[] parts = new Part[paramNames.length + 2];
        parts[paramNames.length] = new FilePart("file", file);
        parts[paramNames.length + 1] = new StringPart("apiKey", propertiesManager.getKey());

        for (int i = 0; i < paramNames.length; i++) {
            parts[i] = new StringPart(paramNames[i], paramVals[i]);
        }

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

        filePost.setContentChunked(true);
        HttpClient client = new HttpClient();
        status = client.executeMethod(filePost);

        if (status != 200) {
            LOGGER.warn("Request for '" + completeUrl + "' status was " + status + ", not 200 as expected.");
        }

        if (status == 302) {
            Header location = filePost.getResponseHeader("Location");
            printRedirectInformation(location);
        }

        response = ResponseParser.getRestResponse(filePost.getResponseBodyAsStream(), status, targetClass);

    } catch (SSLHandshakeException sslHandshakeException) {

        importCert(sslHandshakeException);

    } catch (IOException e1) {
        LOGGER.error("There was an error and the POST request was not finished.", e1);
        response = ResponseParser.getErrorResponse("There was an error and the POST request was not finished.",
                status);
    }

    return response;
}

From source file:fedora.client.FedoraClient.java

/**
 * Upload the given file to Fedora's upload interface via HTTP POST.
 *
 * @return the temporary id which can then be passed to API-M requests as a
 *         URL. It will look like uploaded://123
 *///from   w  w w  .  j ava  2s  . c o m
public String uploadFile(File file) throws IOException {
    PostMethod post = null;
    try {
        // prepare the post method
        post = new PostMethod(getUploadURL());
        post.setDoAuthentication(true);
        post.getParams().setParameter("Connection", "Keep-Alive");

        // chunked encoding is not required by the Fedora server,
        // but makes uploading very large files possible
        post.setContentChunked(true);

        // add the file part
        Part[] parts = { new FilePart("file", file) };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

        // execute and get the response
        int responseCode = getHttpClient().executeMethod(post);
        String body = null;
        try {
            body = post.getResponseBodyAsString();
        } catch (Exception e) {
            LOG.warn("Error reading response body", e);
        }
        if (body == null) {
            body = "[empty response body]";
        }
        body = body.trim();
        if (responseCode != HttpStatus.SC_CREATED) {
            throw new IOException("Upload failed: " + HttpStatus.getStatusText(responseCode) + ": "
                    + replaceNewlines(body, " "));
        } else {
            return replaceNewlines(body, "");
        }
    } finally {
        if (post != null) {
            post.releaseConnection();
        }
    }
}