Example usage for org.apache.commons.httpclient.methods.multipart MultipartRequestEntity MultipartRequestEntity

List of usage examples for org.apache.commons.httpclient.methods.multipart MultipartRequestEntity MultipartRequestEntity

Introduction

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

Prototype

public MultipartRequestEntity(Part[] paramArrayOfPart, HttpMethodParams paramHttpMethodParams) 

Source Link

Usage

From source file:com.sai.b2blogistic.RegisterActivity.java

/**  */
public String uploadPic(String pic_path) {
    PostMethod postMethod = new PostMethod(HttpRestClient.getAbsoluteUrl("/driver/upload"));
    try {//from  w  w w .j ava  2 s. c o  m
        File file = new File(pic_path);
        // FilePart
        FilePart fp = new FilePart("file", file);
        Part[] parts = { fp };

        // MIMEhttpclientMulitPartRequestEntity
        MultipartRequestEntity mre = new MultipartRequestEntity(parts, postMethod.getParams());
        postMethod.setRequestEntity(mre);
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(50000);// 
        int status = client.executeMethod(postMethod);
        if (status == HttpStatus.SC_OK) {
            return postMethod.getResponseBodyAsString();
        } else {
            ToolKits.showShortTips(this, "");
        }
    } catch (Exception e) {
        e.printStackTrace();
        ToolKits.showShortTips(this, "" + e.getMessage());
    } finally {
        // 
        postMethod.releaseConnection();
    }
    return null;
}

From source file:io.fabric8.gateway.servlet.ProxyServlet.java

/**
 * Sets up the given {@link EntityEnclosingMethod} to send the same multipart
 * data as was sent in the given {@link javax.servlet.http.HttpServletRequest}
 *
 * @param entityEnclosingMethod The {@link EntityEnclosingMethod} that we are
 *                               configuring to send a multipart request
 * @param httpServletRequest     The {@link javax.servlet.http.HttpServletRequest} that contains
 *                               the mutlipart data to be sent via the {@link EntityEnclosingMethod}
 *//*w  w w  .  j  a  v  a2 s  .  c om*/
private void handleMultipartPost(EntityEnclosingMethod entityEnclosingMethod,
        HttpServletRequest httpServletRequest) throws ServletException {
    // Create a factory for disk-based file items
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    // Set factory constraints
    diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
    diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY);
    // Create a new file upload handler
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    // Parse the request
    try {
        // Get the multipart items as a list
        List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);
        // Create a list to hold all of the parts
        List<Part> listParts = new ArrayList<Part>();
        // Iterate the multipart items list
        for (FileItem fileItemCurrent : listFileItems) {
            // If the current item is a form field, then create a string part
            if (fileItemCurrent.isFormField()) {
                StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name
                        fileItemCurrent.getString() // The field value
                );
                // Add the part to the list
                listParts.add(stringPart);
            } else {
                // The item is a file upload, so we create a FilePart
                FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name
                        new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name
                                fileItemCurrent.get() // The uploaded file contents
                        ));
                // Add the part to the list
                listParts.add(filePart);
            }
        }
        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(
                listParts.toArray(new Part[] {}), entityEnclosingMethod.getParams());
        entityEnclosingMethod.setRequestEntity(multipartRequestEntity);
        // The current content-type header (received from the client) IS of
        // type "multipart/form-data", but the content-type header also
        // contains the chunk boundary string of the chunks. Currently, this
        // header is using the boundary of the client request, since we
        // blindly copied all headers from the client request to the proxy
        // request. However, we are creating a new request with a new chunk
        // boundary string, so it is necessary that we re-set the
        // content-type string to reflect the new chunk boundary string
        entityEnclosingMethod.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME,
                multipartRequestEntity.getContentType());
    } catch (FileUploadException fileUploadException) {
        throw new ServletException(fileUploadException);
    }
}

From source file:is.idega.block.finance.business.sp.SPDataInsertTest.java

private MultipartPostMethod sendCreateClaimsRequest() {
    /*// w  ww.j  a  v a2  s. c o  m
     * HttpClient client = new HttpClient(); client.setStrictMode(false);
     * MultipartPostMethod post = new MultipartPostMethod(SITE +
     * POST_METHOD); File file = new File(FILE_NAME);
     * 
     * try { post.addParameter("notendanafn", "lolo7452");// "aistest");
     * post.addParameter("password", "12345felix");
     * post.addParameter("KtFelags", "6812933379");// "5709902259");
     * post.addParameter("Skra", file);
     * 
     * post.setDoAuthentication(false); client.executeMethod(post);
     * 
     * System.out.println("responseString: " +
     * post.getResponseBodyAsString()); } catch (FileNotFoundException e1) {
     * e1.printStackTrace(); } catch (IOException e2) {
     * e2.printStackTrace(); } finally { post.releaseConnection(); } return
     * post;
     */

    PostMethod filePost = new PostMethod(SITE + POST_METHOD);
    File file = new File(FILE_NAME);

    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);

    try {
        StringPart userPart = new StringPart("notendanafn", "lolo7452");
        StringPart pwdPart = new StringPart("password", "12345felix");
        StringPart clubssnPart = new StringPart("KtFelags", "6812933379");
        FilePart filePart = new FilePart("Skra", file);

        Part[] parts = { userPart, pwdPart, clubssnPart, filePart };
        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) {
            System.out.println("Upload complete, response=" + filePost.getResponseBodyAsString());
        } else {
            System.out.println("Upload failed, response=" + HttpStatus.getStatusText(status));
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        filePost.releaseConnection();
    }

    return null;

    /*
     * PostMethod authpost = new PostMethod(SITE + POST_METHOD);
     * 
     * authpost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE,
     * true); try {
     * 
     * HttpClient client = new HttpClient();
     * client.getHttpConnectionManager().getParams().setConnectionTimeout(
     * 5000);
     * 
     * File file = new File(FILE_NAME); // Prepare login parameters
     * NameValuePair inputFile = new NameValuePair("xmldata", file);
     * authpost.setRequestBody(new NameValuePair[] { inputFile });
     * 
     * int status = client.executeMethod(authpost); System.out.println("Form
     * post: " + authpost.getStatusLine().toString()); if (status ==
     * HttpStatus.SC_OK) { System.out.println("Submit complete, response=" +
     * authpost.getResponseBodyAsString()); } else {
     * System.out.println("Submit failed, response=" +
     * HttpStatus.getStatusText(status)); } } catch (Exception ex) {
     * ex.printStackTrace(); } finally { authpost.releaseConnection(); }
     */

}

From source file:is.idega.block.finance.business.kb.KBDataInsert.java

/**
 * Sends a http multipart post method to KBBanki to create the claims
 * /*ww w  .j  a v  a2s  . c  o  m*/
 * @param bfm
 * @param groupId
 * @return
 */
private void sendCreateClaimsRequest(BankFileManager bfm) {
    /*      HttpClient client = new HttpClient();
          MultipartPostMethod post = new MultipartPostMethod(POST_METHOD);
          File file = new File(FILE_NAME);
                  
          System.out.println("!!!kb:");
          System.out.println("username = " + bfm.getUsername());
          System.out.println("password = " + bfm.getPassword());
                  
          try {
             post.addParameter("cguser", bfm.getUsername());// "IK66TEST"
             post.addParameter("cgpass", bfm.getPassword());// "KBIK66"
             post.addParameter("cgutli", "0");
             post.addParameter("cgskra", file);
             post.setDoAuthentication(false);
             client.executeMethod(post);
            
             System.out.println("responseString: "
       + post.getResponseBodyAsString());
            
          } catch (FileNotFoundException e1) {
             e1.printStackTrace();
          } catch (IOException e2) {
             e2.printStackTrace();
          } finally {
             post.releaseConnection();
          }
          return post;*/

    PostMethod filePost = new PostMethod(POST_METHOD);
    File file = new File(FILE_NAME);

    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);

    try {
        StringPart userPart = new StringPart("cguser", bfm.getUsername());
        StringPart pwdPart = new StringPart("password", bfm.getPassword());
        StringPart clubssnPart = new StringPart("cgclaimBatchName", batchName);
        FilePart filePart = new FilePart("cgskra", file);

        Part[] parts = { userPart, pwdPart, clubssnPart, filePart };
        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) {
            System.out.println("Upload complete, response=" + filePost.getResponseBodyAsString());
        } else {
            System.out.println("Upload failed, response=" + HttpStatus.getStatusText(status));
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        filePost.releaseConnection();
    }

}

From source file:JiraWebClient.java

public void attachFile(final JiraIssue issue, final String comment, final FilePart filePart,
        final String contentType, IProgressMonitor monitor) throws JiraException {
    doInSession(monitor, new JiraWebSessionCallback() {
        @Override// w w w.  j  a  va 2s . com
        public void run(JiraClient server, String baseUrl, IProgressMonitor monitor) throws JiraException {
            StringBuilder attachFileURLBuffer = new StringBuilder(baseUrl);
            attachFileURLBuffer.append("/secure/AttachFile.jspa"); //$NON-NLS-1$

            PostMethod post = new PostMethod(attachFileURLBuffer.toString());
            prepareSecurityToken(post);

            List<PartBase> parts = new ArrayList<PartBase>();

            StringPart idPart = new StringPart("id", issue.getId()); //$NON-NLS-1$
            StringPart commentLevelPart = new StringPart("commentLevel", ""); //$NON-NLS-1$ //$NON-NLS-2$

            // The transfer encodings have to be removed for some reason
            // There is no need to send the content types for the strings,
            // as they should be in the correct format
            idPart.setTransferEncoding(null);
            idPart.setContentType(null);

            if (comment != null) {
                StringPart commentPart = new StringPart("comment", comment); //$NON-NLS-1$
                commentPart.setTransferEncoding(null);
                commentPart.setContentType(null);
                commentPart.setCharSet(client.getCharacterEncoding(monitor));
                parts.add(commentPart);
            }

            commentLevelPart.setTransferEncoding(null);
            commentLevelPart.setContentType(null);

            filePart.setTransferEncoding(null);
            if (contentType != null) {
                filePart.setContentType(contentType);
            }
            parts.add(filePart);
            parts.add(idPart);
            parts.add(commentLevelPart);

            post.setRequestEntity(
                    new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams()));

            try {
                execute(post);
                if (!expectRedirect(post, "/secure/ManageAttachments.jspa?id=" + issue.getId())) { //$NON-NLS-1$
                    handleErrorMessage(post);
                }
            } finally {
                post.releaseConnection();
            }
        }
    });
}

From source file:edu.harvard.iq.dvn.core.web.dataaccess.HttpAccessObject.java

private String dvnRemoteAuth(String remoteHost) {
    // if successful, this method will return the JSESSION string
    // for the authenticated session on the remote DVN.

    String remoteJsessionid = null;
    String remoteDvnUser = null;/*ww  w.  j  a  v  a2 s.  c o m*/
    String remoteDvnPw = null;

    GetMethod loginGetMethod = null;
    PostMethod loginPostMethod = null;

    RemoteAccessAuth remoteAuth = studyService.lookupRemoteAuthByHost(remoteHost);

    if (remoteAuth == null) {
        return null;
    }

    remoteDvnUser = remoteAuth.getAuthCred1();
    remoteDvnPw = remoteAuth.getAuthCred2();

    if (remoteDvnUser == null || remoteDvnPw == null) {
        return null;
    }

    int status = 0;

    try {

        String remoteAuthUrl = "http://" + remoteHost + "/dvn/faces/login/LoginPage.xhtml";
        loginGetMethod = new GetMethod(remoteAuthUrl);
        loginGetMethod.setFollowRedirects(false);
        status = (new HttpClient()).executeMethod(loginGetMethod);

        InputStream in = loginGetMethod.getResponseBodyAsStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(in));

        String line = null;

        String viewstate = null;

        String regexpJsession = "jsessionid=([^\"?&]*)";
        String regexpViewState = "ViewState\" value=\"([^\"]*)\"";

        Pattern patternJsession = Pattern.compile(regexpJsession);
        Pattern patternViewState = Pattern.compile(regexpViewState);

        Matcher matcher = null;

        while ((line = rd.readLine()) != null) {
            matcher = patternJsession.matcher(line);
            if (matcher.find()) {
                remoteJsessionid = matcher.group(1);
            }
            matcher = patternViewState.matcher(line);
            if (matcher.find()) {
                viewstate = matcher.group(1);
            }
        }

        rd.close();
        loginGetMethod.releaseConnection();

        if (remoteJsessionid != null) {

            // We have found Jsession;
            // now we can log in,
            // has to be a POST method:

            loginPostMethod = new PostMethod(remoteAuthUrl + ";jsessionid=" + remoteJsessionid);
            loginPostMethod.setFollowRedirects(false);

            Part[] parts = { new StringPart("vanillaLoginForm:vdcId", ""),
                    new StringPart("vanillaLoginForm:username", remoteDvnUser),
                    new StringPart("vanillaLoginForm:password", remoteDvnPw),
                    new StringPart("vanillaLoginForm_hidden", "vanillaLoginForm_hidden"),
                    new StringPart("vanillaLoginForm:button1", "Log in"),
                    new StringPart("javax.faces.ViewState", viewstate) };

            loginPostMethod.setRequestEntity(new MultipartRequestEntity(parts, loginPostMethod.getParams()));
            loginPostMethod.addRequestHeader("Cookie", "JSESSIONID=" + remoteJsessionid);
            status = (new HttpClient()).executeMethod(loginPostMethod);

            String redirectLocation = null;

            if (status == 302) {
                for (int i = 0; i < loginPostMethod.getResponseHeaders().length; i++) {
                    String headerName = loginPostMethod.getResponseHeaders()[i].getName();
                    if (headerName.equals("Location")) {
                        redirectLocation = loginPostMethod.getResponseHeaders()[i].getValue();
                    }
                }
            }

            loginPostMethod.releaseConnection();
            int counter = 0;

            int redirectLimit = 20; // number of redirects we are willing to follow before we give up.

            while (status == 302 && counter < redirectLimit) {

                if (counter > 0) {
                    for (int i = 0; i < loginGetMethod.getResponseHeaders().length; i++) {
                        String headerName = loginGetMethod.getResponseHeaders()[i].getName();
                        if (headerName.equals("Location")) {
                            redirectLocation = loginGetMethod.getResponseHeaders()[i].getValue();
                        }
                    }
                }

                // try following redirects until we get a static page,
                // or until we exceed the hoop limit.
                if (redirectLocation.matches(".*TermsOfUsePage.*")) {
                    loginGetMethod = remoteAccessTOU(redirectLocation + "&clicker=downloadServlet",
                            remoteJsessionid, null, null);
                    if (loginGetMethod != null) {
                        status = loginGetMethod.getStatusCode();
                    }
                } else {
                    loginGetMethod = new GetMethod(redirectLocation);
                    loginGetMethod.setFollowRedirects(false);
                    loginGetMethod.addRequestHeader("Cookie", "JSESSIONID=" + remoteJsessionid);
                    status = (new HttpClient()).executeMethod(loginGetMethod);

                    //InputStream in = loginGetMethod.getResponseBodyAsStream();
                    //BufferedReader rd = new BufferedReader(new InputStreamReader(in));
                    //rd.close();
                    loginGetMethod.releaseConnection();
                    counter++;
                }
            }
        }
    } catch (IOException ex) {
        if (loginGetMethod != null) {
            loginGetMethod.releaseConnection();
        }
        if (loginPostMethod != null) {
            loginPostMethod.releaseConnection();
        }
        return null;
    }

    return remoteJsessionid;
}

From source file:com.sun.faban.driver.transport.hc3.ApacheHC3Transport.java

/**
 * Makes a Multi-part POST request to the URL. Reads data back and discards
 * the data, keeping just the size of the total read. This is useful for
 * ensuring receival of binary or text data that do not need further
 * analysis.//  w  ww .  jav  a2s.c om
 *
 * @param url The URL to read from
 * @param parts The parts list
 * @param headers The request headers
 * @return The number of bytes read
 * @throws java.io.IOException
 */
public int readURL(String url, List<Part> parts, Map<String, String> headers) throws IOException {

    Part[] partsArray = parts.toArray(new Part[parts.size()]);
    PostMethod method = new PostMethod(url);
    method.setFollowRedirects(followRedirects);
    setHeaders(method, headers);
    method.setRequestEntity(new MultipartRequestEntity(partsArray, method.getParams()));
    try {
        responseCode = hc.executeMethod(method);
        buildResponseHeaders(method);
        return readResponse(method);
    } finally {
        method.releaseConnection();
    }
}

From source file:edu.ku.brc.specify.plugins.ipadexporter.IPadCloudJSONImpl.java

/**
 * @param valuesMap//from   w ww . j  av  a  2  s. c  om
 * @return
 */
private synchronized JSONObject sendPost(final HashMap<String, String> valuesMap) {
    String writeURLStr = getWriteURL();

    isNetworkError = false;

    //        System.out.println(writeURLStr);
    //        System.out.println("\n------------------------ ");
    //        for (String k : valuesMap.keySet())
    //        {
    //            System.out.println(String.format("[%s] [%s]", k, valuesMap.get(k)));
    //        }
    //        System.out.println("------------------------\n"+writeURLStr);
    //UIRegistry.showError("Cloud URL: "+writeURLStr); // Visual Debugging

    PostMethod post = new PostMethod(writeURLStr);
    try {
        Part[] parts = new Part[valuesMap.size()];
        int i = 0;
        for (String key : valuesMap.keySet()) {
            //System.out.println("key["+key+"] val["+valuesMap.get(key)+"]");
            String val = valuesMap.get(key);
            parts[i++] = new StringPart(key, val == null ? "" : val, "UTF-8");
        }

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

        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
        client.getParams().setParameter("http.protocol.content-charset", "UTF-8");

        //System.out.println("CharSet: "+client.getParams().getHttpElementCharset());
        client.getParams().setHttpElementCharset("UTF-8");
        //System.out.println("CharSet: "+client.getParams().getHttpElementCharset());

        int status = client.executeMethod(post);

        if (status == HttpStatus.SC_OK) {
            System.err.println("HTTP Status: OK");
            String outStr = post.getResponseBodyAsString();
            System.out.println("outStr[" + outStr + "]");

            return JSONObject.fromObject(outStr);
        }

        System.err.println("HTTP Status: " + status);
        System.err.println(post.getResponseBodyAsString());

    } catch (java.net.UnknownHostException uex) {
        isNetworkError = true;

    } catch (Exception ex) {
        System.out.println("Error:  " + ex.getMessage());
        ex.printStackTrace();
        isNetworkError = true;

    } finally {
        post.releaseConnection();
    }
    return null;
}

From source file:ca.uvic.cs.tagsea.statistics.svn.jobs.SVNCommentScanningJob.java

/**
 * @param files/*from ww  w. ja va 2  s . com*/
 */
private IStatus sendFile(File file) {
    String uploadScript = "http://stgild.cs.uvic.ca/cgi-bin/tagSEAUpload.cgi";
    int id = TagSEAPlugin.getDefault().getUserID();
    if (id < 0) {
        id = askForID();
        if (id == 0) {
            //just do nothing.
            return Status.OK_STATUS;
        }
    }
    HttpClient client = new HttpClient();
    IStatus s = Status.OK_STATUS;
    String message = "";

    try {
        PostMethod post = new PostMethod(uploadScript);
        Part[] parts = { new StringPart("KIND", "subversion"),
                new FilePart("MYLAR" + id, file.getName(), file) };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
        int status = client.executeMethod(post);
        String resp = getData(post.getResponseBodyAsStream());
        if (status != 200) {
            message += resp + ";";
            s = new Status(IStatus.ERROR, SVNStatistics.PLUGIN_ID, status, message, null);
        }
    } catch (IOException e) {
        message += file.getAbsolutePath() + " could not be sent;";
        s = new Status(IStatus.ERROR, SVNStatistics.PLUGIN_ID, 0, message, e);
    }

    return s;
}

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;//from  w  w  w .ja v a2  s.c om
    try {
        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();
        }
    }
}