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

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

Introduction

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

Prototype

public void setRequestEntity(RequestEntity paramRequestEntity) 

Source Link

Usage

From source file:com.redhat.demo.CrmTest.java

/**
 * HTTP POST http://localhost:8181/cxf/crm/customerservice/customers is used to upload the contents of
 * the add_customer.xml file to add a new customer to the system.
 * <p/>/*from w  w w .ja  v  a 2  s .co  m*/
 * On the server side, it matches the CustomerService's addCustomer() method
 *
 * @throws Exception
 */
@Test
public void postCustomerTest() throws IOException {
    LOG.info("Sent HTTP POST request to add customer");
    String inputFile = this.getClass().getResource("/add_customer.xml").getFile();
    File input = new File(inputFile);
    PostMethod post = new PostMethod(CUSTOMER_SERVICE_URL);
    post.addRequestHeader("Accept", "application/xml");
    RequestEntity entity = new FileRequestEntity(input, "application/xml; charset=ISO-8859-1");
    post.setRequestEntity(entity);
    HttpClient httpclient = new HttpClient();
    String res = "";

    try {
        int result = httpclient.executeMethod(post);
        LOG.info("Response status code: " + result);
        LOG.info("Response body: ");
        res = post.getResponseBodyAsString();
        LOG.info(res);
    } catch (IOException e) {
        LOG.error("Error connecting to {}", CUSTOMER_SERVICE_URL);
        LOG.error(
                "You should build the 'rest' quick start and deploy it to a local Fabric8 before running this test");
        LOG.error("Please read the README.md file in 'rest' quick start root");
        Assert.fail("Connection error");
    } finally {
        // Release current connection to the connection pool once you are
        // done
        post.releaseConnection();
    }
    Assert.assertTrue(res.contains("Jack"));

}

From source file:com.redhat.demo.CrmTest.java

/**
 * HTTP POST http://localhost:8181/cxf/crm/customerservice/customers is used to upload the contents of
 * the add_customer.json file to add a new customer to the system.
 * <p/>//ww  w .j  a v  a  2 s . co m
 * On the server side, it matches the CustomerService's addCustomer() method
 *
 * @throws Exception
 */
@Test
public void postCustomerTestJson() throws IOException {
    LOG.info("Sent HTTP POST request to add customer");
    String inputFile = this.getClass().getResource("/add_customer.json").getFile();
    File input = new File(inputFile);
    PostMethod post = new PostMethod(CUSTOMER_SERVICE_URL);
    post.addRequestHeader("Accept", "application/json");
    RequestEntity entity = new FileRequestEntity(input, "application/json; charset=ISO-8859-1");
    post.setRequestEntity(entity);
    HttpClient httpclient = new HttpClient();
    String res = "";

    try {
        int result = httpclient.executeMethod(post);
        LOG.info("Response status code: " + result);
        LOG.info("Response body: ");
        res = post.getResponseBodyAsString();
        LOG.info(res);
    } catch (IOException e) {
        LOG.error("Error connecting to {}", CUSTOMER_SERVICE_URL);
        LOG.error(
                "You should build the 'rest' quick start and deploy it to a local Fabric8 before running this test");
        LOG.error("Please read the README.md file in 'rest' quick start root");
        Assert.fail("Connection error");
    } finally {
        // Release current connection to the connection pool once you are
        // done
        post.releaseConnection();
    }
    Assert.assertTrue(res.contains("Jack"));

}

From source file:ca.uvic.cs.tagsea.monitor.NetworkLogging.java

public synchronized boolean uploadForDate(Date d) throws IOException {
    File f = SimpleDayLog.findLogFileForDay(d);
    if (f.length() == 0)
        return true;

    PostMethod post = new PostMethod(uploadScript);
    Display disp = TagSEAMonitorPlugin.getDefault().getWorkbench().getDisplay();
    int id = getUID();
    if (id < 0) {
        //error getting the user id. Quit.
        return false;
    }//from   w  ww . j a  va2  s  .c o m
    Part[] parts = { new StringPart("KIND", "log"), new FilePart("MYLAR" + id, f.getName(), f) };
    post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
    HttpClient client = new HttpClient();
    int status = client.executeMethod(post);
    resp = getData(post.getResponseBodyAsStream());
    if (status != 200) {
        disp.syncExec(new Runnable() {
            public void run() {
                MessageDialog.openError(null, "Error Sending File", resp);
            }
        });
        return false;

    }
    MonitorPreferences.setLastSendDate(d);
    return true;

}

From source file:com.sap.netweaver.porta.core.nw7.FileUploaderImpl.java

public String[] upload(File[] archives) throws CoreException {
    // check if there are any credentials already set
    if (client == null) {
        // trigger the mechanism for requesting user for credentials
        throw new NotAuthorizedException(FAULT_UNAUTHORIZED.getFaultReason());
    }/*from  w  w w  .  java 2 s .  c om*/

    PostMethod method = null;
    try {
        Part[] parts = new Part[archives.length];
        for (int i = 0; i < archives.length; i++) {
            parts[i] = new FilePart(archives[i].getName(), archives[i]);
        }

        method = new PostMethod(url);
        method.setDoAuthentication(true);
        method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));

        int statusCode = client.executeMethod(method);
        if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            throw new NotAuthorizedException(FAULT_INVALID_CREDENTIALS.getFaultReason());
        } else if (statusCode == HttpStatus.SC_FORBIDDEN) {
            throw new NotAuthorizedException(FAULT_PERMISSION_DENIED.getFaultReason());
        } else if (statusCode == HttpStatus.SC_NOT_FOUND) {
            throw new NoWSGateException(null, url);
        } else if (statusCode != HttpStatus.SC_OK) {
            throw new CoreException(method.getStatusText());
        }

        InputStream responseStream = method.getResponseBodyAsStream();
        BufferedReader responseReader = new BufferedReader(new InputStreamReader(responseStream));
        String line;
        List<String> paths = new ArrayList<String>();
        while ((line = responseReader.readLine()) != null) {
            paths.add(line);
        }
        responseReader.close();
        responseStream.close();

        return paths.toArray(new String[] {});
    } catch (HttpException e) {
        throw new CoreException(e);
    } catch (IOException e) {
        throw new CoreException(e);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:com.nokia.helium.diamonds.DiamondsSessionSocket.java

/**
 * Internal method to send data to diamonds.
 * If ignore result is true, then the method will return null, else the message return by the query
 * will be returned.//from www . ja  v a 2  s .c o  m
 * @param message
 * @param ignoreResult
 * @return
 * @throws DiamondsException is thrown in case of message retrieval error, connection error. 
 */
protected synchronized String sendInternal(Message message, boolean ignoreResult) throws DiamondsException {
    URL destURL = url;
    if (buildId != null) {
        try {
            destURL = new URL(url.getProtocol(), url.getHost(), url.getPort(), buildId);
        } catch (MalformedURLException e) {
            throw new DiamondsException("Error generating the url to send the message: " + e.getMessage(), e);
        }
    }
    PostMethod post = new PostMethod(destURL.toExternalForm());
    try {
        File tempFile = streamToTempFile(message.getInputStream());
        tempFile.deleteOnExit();
        messages.add(tempFile);
        post.setRequestEntity(new FileRequestEntity(tempFile, "text/xml"));
    } catch (MessageCreationException e) {
        throw new DiamondsException("Error retrieving the message: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new DiamondsException("Error serializing the message into a temporary file: " + e.getMessage(),
                e);
    }
    try {
        int result = httpClient.executeMethod(post);
        if (result != HttpStatus.SC_OK && result != HttpStatus.SC_ACCEPTED) {
            throw new DiamondsException("Error sending the message: " + post.getStatusLine() + "("
                    + post.getResponseBodyAsString() + ")");
        }
        if (!ignoreResult) {
            return post.getResponseBodyAsString();
        }
    } catch (HttpException e) {
        throw new DiamondsException("Error sending the message: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new DiamondsException("Error sending the message: " + e.getMessage(), e);
    } finally {
        post.releaseConnection();
    }
    return null;
}

From source file:$.CrmTest.java

/**
     * HTTP POST http://localhost:8181/cxf/crm/customerservice/customers is used to upload the contents of
     * the add_customer.xml file to add a new customer to the system.
     * <p/>//  www .j  a va 2s. c  o m
     * On the server side, it matches the CustomerService's addCustomer() method
     *
     * @throws Exception
     */
    @Test
    public void postCustomerTest() throws IOException {
        LOG.info("Sent HTTP POST request to add customer");
        String inputFile = this.getClass().getResource("/add_customer.xml").getFile();
        File input = new File(inputFile);
        PostMethod post = new PostMethod(CUSTOMER_SERVICE_URL);
        post.addRequestHeader("Accept", "application/xml");
        RequestEntity entity = new FileRequestEntity(input, "application/xml; charset=ISO-8859-1");
        post.setRequestEntity(entity);
        HttpClient httpclient = new HttpClient();
        String res = "";

        try {
            int result = httpclient.executeMethod(post);
            LOG.info("Response status code: " + result);
            LOG.info("Response body: ");
            res = post.getResponseBodyAsString();
            LOG.info(res);
        } catch (IOException e) {
            LOG.error("Error connecting to {}", CUSTOMER_SERVICE_URL);
            LOG.error(
                    "You should build the 'cxf-cdi' quick start and deploy it to a local Fabric8 before running this test");
            LOG.error("Please read the README.md file in 'cxf-cdi' quick start root");
            Assert.fail("Connection error");
        } finally {
            // Release current connection to the connection pool once you are
            // done
            post.releaseConnection();
        }
        Assert.assertTrue(res.contains("Jack"));

    }

From source file:$.CrmTest.java

/**
     * HTTP POST http://localhost:8181/cxf/crm/customerservice/customers is used to upload the contents of
     * the add_customer.json file to add a new customer to the system.
     * <p/>/*from   w  w w.ja va 2s . c o  m*/
     * On the server side, it matches the CustomerService's addCustomer() method
     *
     * @throws Exception
     */
    @Test
    public void postCustomerTestJson() throws IOException {
        LOG.info("Sent HTTP POST request to add customer");
        String inputFile = this.getClass().getResource("/add_customer.json").getFile();
        File input = new File(inputFile);
        PostMethod post = new PostMethod(CUSTOMER_SERVICE_URL);
        post.addRequestHeader("Accept", "application/json");
        RequestEntity entity = new FileRequestEntity(input, "application/json; charset=ISO-8859-1");
        post.setRequestEntity(entity);
        HttpClient httpclient = new HttpClient();
        String res = "";

        try {
            int result = httpclient.executeMethod(post);
            LOG.info("Response status code: " + result);
            LOG.info("Response body: ");
            res = post.getResponseBodyAsString();
            LOG.info(res);
        } catch (IOException e) {
            LOG.error("Error connecting to {}", CUSTOMER_SERVICE_URL);
            LOG.error(
                    "You should build the 'cxf-cdi' quick start and deploy it to a local Fabric8 before running this test");
            LOG.error("Please read the README.md file in 'cxf-cdi' quick start root");
            Assert.fail("Connection error");
        } finally {
            // Release current connection to the connection pool once you are
            // done
            post.releaseConnection();
        }
        Assert.assertTrue(res.contains("Jack"));

    }

From source file:com.cloudbees.jenkins.plugins.gogs.server.client.GogsServerAPIClient.java

private String postRequest(String path, NameValuePair[] params) throws UnsupportedEncodingException {
    PostMethod httppost = new PostMethod(this.baseURL + path);
    httppost.setRequestEntity(new StringRequestEntity(nameValueToJson(params), "application/json", "UTF-8"));
    return postRequest(httppost);
}

From source file:com.cloudbees.jenkins.plugins.gogs.server.client.GogsServerAPIClient.java

private String postRequest(String path, String content) throws UnsupportedEncodingException {
    PostMethod httppost = new PostMethod(this.baseURL + path);
    httppost.setRequestEntity(new StringRequestEntity(content, "application/json", "UTF-8"));
    return postRequest(httppost);
}

From source file:com.openkm.extension.servlet.ZohoServlet.java

/**
 *   //from  w w w  .j a v  a2 s . c o m
 */
private Map<String, String> sendToZoho(String zohoUrl, String nodeUuid, String lang)
        throws PathNotFoundException, AccessDeniedException, RepositoryException, DatabaseException,
        IOException, OKMException {
    Map<String, String> result = new HashMap<String, String>();
    File tmp = null;

    try {
        String path = OKMRepository.getInstance().getNodePath(null, nodeUuid);
        String fileName = PathUtils.getName(path);
        tmp = File.createTempFile("okm", ".tmp");
        InputStream is = OKMDocument.getInstance().getContent(null, path, false);
        Document doc = OKMDocument.getInstance().getProperties(null, path);
        FileOutputStream fos = new FileOutputStream(tmp);
        IOUtils.copy(is, fos);
        fos.flush();
        fos.close();

        String id = UUID.randomUUID().toString();
        String saveurl = Config.APPLICATION_BASE + "/extension/ZohoFileUpload";
        Part[] parts = { new FilePart("content", tmp), new StringPart("apikey", Config.ZOHO_API_KEY),
                new StringPart("output", "url"), new StringPart("mode", "normaledit"),
                new StringPart("filename", fileName), new StringPart("skey", Config.ZOHO_SECRET_KEY),
                new StringPart("lang", lang), new StringPart("id", id),
                new StringPart("format", getFormat(doc.getMimeType())), new StringPart("saveurl", saveurl) };

        PostMethod filePost = new PostMethod(zohoUrl);
        filePost.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        int status = client.executeMethod(filePost);

        if (status == HttpStatus.SC_OK) {
            log.debug("OK: " + filePost.getResponseBodyAsString());
            ZohoToken zot = new ZohoToken();
            zot.setId(id);
            zot.setUser(getThreadLocalRequest().getRemoteUser());
            zot.setNode(nodeUuid);
            zot.setCreation(Calendar.getInstance());
            ZohoTokenDAO.create(zot);

            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(filePost.getResponseBodyAsStream()));
            String line;

            while ((line = rd.readLine()) != null) {
                if (line.startsWith("URL=")) {
                    result.put("url", line.substring(4));
                    result.put("id", id);
                    break;
                }
            }

            rd.close();
        } else {
            String error = HttpStatus.getStatusText(status) + "\n\n" + filePost.getResponseBodyAsString();
            log.error("ERROR: {}", error);
            throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMZohoService, ErrorCode.CAUSE_Zoho), error);
        }
    } finally {
        FileUtils.deleteQuietly(tmp);
    }

    return result;
}