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:my.swingconnect.SwingConnectUI.java

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
    {// w  ww .ja  v a  2  s. com

        int i = 0;
        while (i < results.size()) {
            String path = results.get(i);
            System.out.println("Printing path" + path);
            targetFile1 = new File(path);

            //                    String targetURL = jTextField3.getSelectedItem().toString();
            //                String targetURL = jTextField3.getSelectedText();
            String targetURL = "http://photo-drop.com/uploader.php";

            //                    if (!targetURL
            //
            //                            .equals(
            //
            //                            cmbURLModel.getElementAt(
            //
            //                            cmbURL.getSelectedIndex()))) {
            //
            //                        cmbURLModel.addElement(targetURL);
            //
            //                    }

            System.out.println(targetURL);
            //From the apache package: the class that implements POST method

            PostMethod filePost = new PostMethod(targetURL);

            filePost.getParams().setBooleanParameter(

                    HttpMethodParams.USE_EXPECT_CONTINUE,

                    jCheckBox1.isSelected());
            try {

                System.out.println("Uploading " + targetFile1.getName() + " to " + targetURL);
                jTextArea2.append("Uploading " + targetFile1.getName() + " to " + targetURL);
                filename = targetFile1.toString();
                System.out.println(filename);
                javapostmethod f = new javapostmethod();
                f.sendPost(filename);

                Part[] parts = {

                        new FilePart(targetFile1.getName(), targetFile1)

                };

                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) {
                    jTextArea2.append("Upload complete, response=" + filePost.getResponseBodyAsString());
                    jTextArea2.append("Uploaded from:" + filename);
                } else {
                    jTextArea2.append("Upload failed, response=" + HttpStatus.getStatusText(status));
                }
            } catch (Exception ex) {
                jTextArea2.append("Error: " + ex.getMessage());
                ex.printStackTrace();
            } finally {
                filePost.releaseConnection();
            }

            i++;

        }

        //

    }

}

From source file:hoot.services.controllers.ogr.TranslatorResource.java

/**
 * <NAME>OGR-LTDS Translation Service Translate TDS to OSM</NAME>
 * <DESCRIPTION>// ww w .  j a  va2 s . c om
 * WARNING: THIS END POINT WILL BE DEPRECATED SOON
 * Translate TDS to OSM
 *  http://localhost:8080/hoot-services/ogr/ltds/translate/tds/{OSM element id}?translation={translation script}
 * </DESCRIPTION>
 * <PARAMETERS>
 * <translation>
 *    relative path of translation script
 * </translation>
 * </PARAMETERS>
 * <OUTPUT>
 *    TDS output
 * </OUTPUT>
 * <EXAMPLE>
 *    <URL>http://localhost:8080/hoot-services/ogr/ltds/translate/-1669795?translation=MGCP.js</URL>
 *    <REQUEST_TYPE>POST</REQUEST_TYPE>
 *    <INPUT>
 * {"attrs":{"FCODE":"AP030","HCT":"0","UID":"d9c4b1df-066c-4ece-a583-76fec0056b58"},"tableName":"LAP030"}
 *   </INPUT>
 * <OUTPUT>OSM XML output</OUTPUT>
 * </EXAMPLE>
* @param id
* @param translation
* @param osmXml
* @return
*/
@POST
@Path("/ltds/translate/tds/{id}")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
public Response translateTdsToOsm(@PathParam("id") String id,
        @QueryParam("translation") final String translation, String osmXml) {
    String outStr = "unknown";
    PostMethod mpost = new PostMethod("http://localhost:" + currentPort + "/tdstoosm");
    try {

        try {

            String ogrxml = osmXml.replace('"', '\'');

            JSONObject requestParams = new JSONObject();
            requestParams.put("command", "translate");
            requestParams.put("uid", id);
            requestParams.put("input", ogrxml);
            requestParams.put("script", homeFolder + "/translations" + translation);
            requestParams.put("direction", "toogr");
            String postData = requestParams.toJSONString();
            StringEntity se = new StringEntity(requestParams.toJSONString());
            StringRequestEntity requestEntity = new StringRequestEntity(requestParams.toJSONString(),
                    "text/plain", "UTF-8");
            mpost.setRequestEntity(requestEntity);

            mclient.executeMethod(mpost);
            String response = mpost.getResponseBodyAsString();

            JSONParser par = new JSONParser();
            JSONObject transRes = (JSONObject) par.parse(response);
            String tdsOSM = transRes.get("output").toString();
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            StringReader strReader = new StringReader(tdsOSM);
            InputSource is = new InputSource(strReader);

            Document document = builder.parse(is);
            strReader.close();

            JSONObject attrib = new JSONObject();
            NodeList nodeList = document.getDocumentElement().getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (node instanceof Element) {
                    NodeList childNodes = node.getChildNodes();
                    for (int j = 0; j < childNodes.getLength(); j++) {
                        Node cNode = childNodes.item(j);
                        if (cNode instanceof Element) {
                            String k = ((Element) cNode).getAttribute("k");
                            String v = ((Element) cNode).getAttribute("v");
                            attrib.put(k, v);

                        }
                    }
                }
            }

            JSONObject ret = new JSONObject();
            ret.put("tablenName", "");
            ret.put("attrs", attrib);
            outStr = ret.toJSONString();

        } catch (Exception ee) {
            ResourceErrorHandler.handleError("Failed upload: " + ee.toString(), Status.INTERNAL_SERVER_ERROR,
                    log);
        } finally {
            log.debug("postJobRequest Closing");
            mpost.releaseConnection();
        }

    } catch (Exception e) {
        ResourceErrorHandler.handleError("Translation error: " + e.toString(), Status.INTERNAL_SERVER_ERROR,
                log);
    }

    return Response.ok(outStr, MediaType.APPLICATION_JSON).build();
}

From source file:net.sourceforge.jwbf.actions.mw.editing.FileUpload.java

/**
 * /*  w ww  . j a va 2 s  .  c  o  m*/
 * @param a the
 * @param tab internal value set
 * @param login a 
 * @throws ActionException on problems with file
 */
public FileUpload(final SimpleFile a, final Hashtable<String, String> tab, LoginData login)
        throws ActionException {

    if (!a.getFile().isFile() || !a.getFile().canRead()) {
        throw new ActionException("no such file " + a.getFile());
    }

    String uS = "";
    // try {
    uS = "/Spezial:Hochladen";
    uS = "/index.php?title=Special:Upload";
    // uS = "/index.php?title=" + URLEncoder.encode("Spezial:Hochladen",
    // MediaWikiBot.CHARSET);
    // + "&action=submit";
    // } catch (UnsupportedEncodingException e) {
    // e.printStackTrace();
    // }

    try {

        LOG.info("WRITE: " + a.getLabel());
        PostMethod post = new PostMethod(uS);
        Part[] parts;
        if (a.getText().isEmpty()) {
            parts = new Part[] { new StringPart("wpDestFile", a.getLabel()),
                    new StringPart("wpIgnoreWarning", "true"), new StringPart("wpSourceType", "file"),
                    new StringPart("wpUpload", "Upload file"),
                    // new StringPart("wpUploadDescription", "false"),
                    // new StringPart("wpWatchthis", "false"),

                    new FilePart("wpUploadFile", a.getFile())
                    // new FilePart( f.getName(), f)

            };
        } else {
            parts = new Part[] { new StringPart("wpDestFile", a.getLabel()),
                    new StringPart("wpIgnoreWarning", "true"), new StringPart("wpSourceType", "file"),
                    new StringPart("wpUpload", "Upload file"),
                    // new StringPart("wpUploadDescription", "false"),
                    // new StringPart("wpWatchthis", "false"),

                    new FilePart("wpUploadFile", a.getFile()),
                    // new FilePart( f.getName(), f)
                    new StringPart("wpUploadDescription", a.getText()) };

        }
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

        // int statusCode = hc.executeMethod(post);
        // log(statusCode);

        // log(Arrays.asList(post.getResponseHeaders()));
        //
        // String res = post.getResponseBodyAsString();
        // LOG.debug(res);
        // post.releaseConnection();
        // pm.setRequestBody(new NameValuePair[] { action, wpStarttime,
        // wpEditToken, wpEdittime, wpTextbox, wpSummary, wpMinoredit });
        msgs.add(post);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:edu.unc.lib.dl.fedora.ManagementClient.java

public String upload(File file, boolean retry) {
    String result = null;/*  w  ww.ja v  a2 s.  c om*/
    String uploadURL = this.getFedoraContextUrl() + "/upload";
    PostMethod post = new PostMethod(uploadURL);
    post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
    log.debug("Uploading file with forwarded groups: " + GroupsThreadStore.getGroupString());
    post.addRequestHeader(HttpClientUtil.FORWARDED_GROUPS_HEADER, GroupsThreadStore.getGroupString());
    try {
        log.debug("Uploading to " + uploadURL);
        Part[] parts = { new FilePart("file", file) };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
        int status = httpClient.executeMethod(post);

        StringWriter sw = new StringWriter();
        try (InputStream in = post.getResponseBodyAsStream(); PrintWriter pw = new PrintWriter(sw)) {
            int b;
            while ((b = in.read()) != -1) {
                pw.write(b);
            }
        }

        switch (status) {
        case HttpStatus.SC_OK:
        case HttpStatus.SC_CREATED:
        case HttpStatus.SC_ACCEPTED:
            result = sw.toString().trim();
            log.info("Upload complete, response=" + result);
            break;
        case HttpStatus.SC_FORBIDDEN:
            log.warn("Authorization to Fedora failed, attempting to reestablish connection.");
            try {
                this.initializeConnections();
                return upload(file, false);
            } catch (Exception e) {
                log.error("Failed to reestablish connection to Fedora", e);
            }
            break;
        case HttpStatus.SC_SERVICE_UNAVAILABLE:
            throw new FedoraTimeoutException("Fedora service unavailable, upload failed");
        default:
            log.warn("Upload failed, response=" + HttpStatus.getStatusText(status));
            log.debug(sw.toString().trim());
            break;
        }
    } catch (ServiceException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new ServiceException(ex);
    } finally {
        post.releaseConnection();
    }
    return result;
}

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

protected String executeUpload(String uploadURL, Map<String, String> params, Map<String, File> files,
        UploadProgress writeListener) throws Exception {
    HashMap<String, String> clientParams = getDefaultParameters();
    clientParams.putAll(params);/*w w  w  .  j av a 2s. co m*/

    PostMethod filePost = new PostMethod(uploadURL);
    try {
        ArrayList<Part> parts = new ArrayList<Part>();

        int fileUploadSize = 0;
        for (Map.Entry<String, File> fileEntry : files.entrySet()) {
            FilePart filePart = new FilePart(fileEntry.getKey(), fileEntry.getValue());
            parts.add(filePart);
            fileUploadSize += filePart.length();
            //TODO: file params are not currently included in the signature,
            //      we should hash the file contents so we can verify them
        }

        for (Map.Entry<String, String> entry : clientParams.entrySet()) {
            parts.add(new StringPart(entry.getKey(), entry.getValue()));
        }

        // add the signature
        String signature = calculateSignature(clientParams);
        parts.add(new StringPart("sig", signature));

        ProgressUploadEntity uploadEntity = new ProgressUploadEntity(parts.toArray(new Part[parts.size()]),
                filePost.getParams(), writeListener, fileUploadSize);
        filePost.setRequestEntity(uploadEntity);
        HttpClient client = HttpClientHelper.createClient(this.beesClientConfiguration);
        client.getHttpConnectionManager().getParams().setConnectionTimeout(10000);

        int status = client.executeMethod(filePost);
        String response = getResponseString(filePost.getResponseBodyAsStream());
        if (status == HttpStatus.SC_OK) {
            trace("upload complete, response=" + response);
        } else {
            trace("upload failed, response=" + HttpStatus.getStatusText(status));
        }
        return response;
    } finally {
        filePost.releaseConnection();
    }
}

From source file:edu.unc.lib.dl.fedora.ManagementClient.java

public String upload(byte[] bytes, String fileName) {
    String result = null;/*from w w  w  . ja  v  a  2 s.  c o  m*/
    // construct a post request to Fedora upload service
    String uploadURL = this.getFedoraContextUrl() + "/upload";
    PostMethod post = new PostMethod(uploadURL);
    post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
    log.debug("Uploading XML with forwarded groups: " + GroupsThreadStore.getGroupString());
    post.addRequestHeader(HttpClientUtil.FORWARDED_GROUPS_HEADER, GroupsThreadStore.getGroupString());
    try {
        log.debug("Uploading to " + uploadURL);
        Part[] parts = { new FilePart("file", new ByteArrayPartSource(fileName, bytes)) };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

        int status = httpClient.executeMethod(post);

        StringWriter sw = new StringWriter();
        try (InputStream in = post.getResponseBodyAsStream(); PrintWriter pw = new PrintWriter(sw)) {
            int b;
            while ((b = in.read()) != -1) {
                pw.write(b);
            }
        }
        if (status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED || status == HttpStatus.SC_ACCEPTED) {
            result = sw.toString().trim();
            log.debug("Upload complete, response=" + result);
        } else {
            log.warn("Upload failed, response=" + HttpStatus.getStatusText(status));
            log.debug(sw.toString().trim());
        }
    } catch (Exception ex) {
        log.error("Upload failed due to error", ex);
        throw new ServiceException(ex);
    } finally {
        post.releaseConnection();
    }
    return result;
}

From source file:muki.tool.JavaCompilationDeploymentTestCase.java

@Test
public void testPostOperation5Xml() throws Exception {
    String url = URL_RESOURCE1 + "/pathPostOperation5Xml";
    PostMethod method = new PostMethod(url);
    String param = this.getXmlCd();
    method.setRequestEntity(new StringRequestEntity(param, "application/xml", null));

    int statusCode = this.getHttpClient().executeMethod(method);
    assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_NO_CONTENT);
    byte[] responseBody = method.getResponseBody();
    assertNull(responseBody);/*from  ww  w.  j  a v  a 2s . co m*/
}

From source file:muki.tool.JavaCompilationDeploymentTestCase.java

@Test
public void testPostOperation5Json() throws Exception {
    String url = URL_RESOURCE1 + "/pathPostOperation5Json";
    PostMethod method = new PostMethod(url);
    String param = this.getJsonCd();
    method.setRequestEntity(new StringRequestEntity(param, "application/json", null));

    int statusCode = this.getHttpClient().executeMethod(method);
    assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_NO_CONTENT);
    byte[] responseBody = method.getResponseBody();
    assertNull(responseBody);/* w  ww  . j  av a  2s .com*/
}

From source file:muki.tool.JavaCompilationDeploymentTestCase.java

@Test
public void testPostOperation7Xml() throws Exception {
    String url = URL_RESOURCE1 + "/pathPostOperation7Xml";
    PostMethod method = new PostMethod(url);
    String param = this.getXmlCd();
    method.setRequestEntity(new StringRequestEntity(param, "application/xml", null));

    int statusCode = this.getHttpClient().executeMethod(method);
    assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_OK);
    byte[] responseBody = method.getResponseBody();
    String xmlResponse = new String(responseBody);
    assertTrue(xmlResponse.indexOf("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>") > -1);
    assertTrue(xmlResponse.indexOf("<title>My Track 1</title>") > -1);
}

From source file:muki.tool.JavaCompilationDeploymentTestCase.java

@Test
public void testPostOperation7Json() throws Exception {
    String url = URL_RESOURCE1 + "/pathPostOperation7Json";
    PostMethod method = new PostMethod(url);
    String param = this.getJsonCd();
    method.setRequestEntity(new StringRequestEntity(param, "application/json", null));

    int statusCode = this.getHttpClient().executeMethod(method);
    assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_OK);
    byte[] responseBody = method.getResponseBody();
    String jsonResponse = new String(responseBody);
    assertTrue(jsonResponse.indexOf("\"title\":\"My Track 1\"") > -1);
}