List of usage examples for org.apache.commons.httpclient.methods.multipart MultipartRequestEntity MultipartRequestEntity
public MultipartRequestEntity(Part[] paramArrayOfPart, HttpMethodParams paramHttpMethodParams)
From source file:com.globalsight.everest.webapp.applet.admin.customer.FileSystemApplet.java
/** * Zip the selected files and send the zip to the server. * @param p_filesToBeZipped - A list of selected files to be uploaded. * @param p_targetURL - The target URL representing server URL. * @param p_targetLocation - A string representing the link to the next page. *///from w w w . jav a 2 s .co m public void sendZipFile(File[] p_filesToBeZipped, String p_targetURL, final String p_targetLocation) throws Exception { StringBuffer sb = new StringBuffer(); sb.append("GS_"); sb.append(System.currentTimeMillis()); sb.append(".zip"); File targetFile = getFile(sb.toString()); ZipIt.addEntriesToZipFile(targetFile, p_filesToBeZipped); m_progressBar.setValue(30); PostMethod filePost = new PostMethod(p_targetURL + "&doPost=true"); filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true); filePost.setDoAuthentication(true); try { Part[] parts = { new FilePart(targetFile.getName(), targetFile) }; m_progressBar.setValue(40); filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); setUpClientForProxy(client); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); m_progressBar.setValue(50); int status = client.executeMethod(filePost); if (status == HttpStatus.SC_OK) { //no need to ask for auth again since the first upload was fine s_authPrompter.setAskForAuthentication(false); m_progressBar.setValue(60); InputStream is = filePost.getResponseBodyAsStream(); m_progressBar.setValue(70); ObjectInputStream inputStreamFromServlet = new ObjectInputStream(is); Vector incomingData = (Vector) inputStreamFromServlet.readObject(); inputStreamFromServlet.close(); if (incomingData != null) { if (incomingData.elementAt(0) instanceof ExceptionMessage) { resetProgressBar(); AppletHelper.displayErrorPage((ExceptionMessage) incomingData.elementAt(0), this); } } else { boolean deleted = targetFile.delete(); m_progressBar.setValue(100); try { Thread.sleep(1000); } catch (Exception e) { } // now move to some other page... goToTargetPage(p_targetLocation); } } else { //authentication may have failed, reset the need to ask s_authPrompter.setAskForAuthentication(true); resetProgressBar(); String errorMessage = "Upload failed because: (" + status + ") " + HttpStatus.getStatusText(status); if (status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) { errorMessage = "Incorrect NTDomain\\username or password entered. Hit 'upload' again to re-try."; } AppletHelper.getErrorDlg(errorMessage, null); } } catch (Exception ex) { //authentication may have failed, reset the need to ask s_authPrompter.setAskForAuthentication(true); resetProgressBar(); System.err.println(ex); AppletHelper.getErrorDlg(ex.getMessage(), null); } finally { filePost.releaseConnection(); } }
From source file:fr.eurecom.nerd.core.proxy.ExtractivClient.java
private static PostMethod getExtractivProcessString(final URI extractivURI, final String content, final String serviceKey) throws FileNotFoundException { final PartBase filePart = new StringPart("content", content, null); // bytes to upload final ArrayList<Part> message = new ArrayList<Part>(); message.add(filePart);/*from w ww . ja v a 2 s .com*/ message.add(new StringPart("formids", "content")); message.add(new StringPart("output_format", "JSON")); message.add(new StringPart("api_key", serviceKey)); final Part[] messageArray = message.toArray(new Part[0]); // Use a Post for the file upload final PostMethod postMethod = new PostMethod(extractivURI.toString()); postMethod.setRequestEntity(new MultipartRequestEntity(messageArray, postMethod.getParams())); postMethod.addRequestHeader("Accept-Encoding", "gzip"); // Request the response be compressed (this is highly recommended) return postMethod; }
From source file:cn.newtouch.util.HttpClientUtil.java
/** * /*from ww w . j a va 2 s .c om*/ * * * @since 2012-1-8 * @param url * URL?URL? * @param file * * @param fileFieldName * forminputname * * @param params * ??? * @throws Exception */ public static void uploadFile(String url, File file, String fileFieldName, Map<String, String> params) throws Exception { String targetURL = url;// URL File targetFile = file;// PostMethod filePost = new PostMethod(targetURL); try { List<StringPart> strPartList = new ArrayList<StringPart>(); // ??? Set<String> keys = params.keySet(); for (String key : keys) { StringPart sp = new StringPart(key, params.get(key), "utf-8"); strPartList.add(sp); } Part[] parts = new Part[1 + strPartList.size()]; parts[0] = new FilePart(fileFieldName, targetFile); for (int i = 0; i < strPartList.size(); i++) { parts[i + 1] = strPartList.get(i); } 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("?"); // ? } else { System.out.println(""); throw new Exception("?" + status); // } } catch (Exception e) { e.printStackTrace(); throw new Exception("" + e.getMessage()); } finally { filePost.releaseConnection(); } }
From source file:edu.wisc.ssec.mcidasv.supportform.Submitter.java
/** * Attempts to {@code POST} to {@code url} using the information from * {@code form}./*from w ww. j av a 2 s. com*/ * * @param url URL that'll accept the {@code POST}. Typically * {@link #requestUrl}. * @param form The {@link SupportForm} that contains the data to use in the * support request. * * @return Big honkin' object that contains the support request. */ private static PostMethod buildPostMethod(String url, SupportForm form) { PostMethod method = new PostMethod(url); List<Part> parts = new ArrayList<Part>(); parts.add(new StringPart("form_data[fromName]", form.getUser())); parts.add(new StringPart("form_data[email]", form.getEmail())); parts.add(new StringPart("form_data[organization]", form.getOrganization())); parts.add(new StringPart("form_data[subject]", form.getSubject())); parts.add(new StringPart("form_data[description]", form.getDescription())); parts.add(new StringPart("form_data[submit]", "")); parts.add(new StringPart("form_data[p_version]", "p_version=ignored")); parts.add(new StringPart("form_data[opsys]", "opsys=ignored")); parts.add(new StringPart("form_data[hardware]", "hardware=ignored")); parts.add(new StringPart("form_data[cc_user]", Boolean.toString(form.getSendCopy()))); // attach the files the user has explicitly attached. if (form.hasAttachmentOne()) { parts.add(buildRealFilePart("form_data[att_two]", form.getAttachmentOne())); } if (form.hasAttachmentTwo()) { parts.add(buildRealFilePart("form_data[att_three]", form.getAttachmentTwo())); } // if the user wants, attach an XML bundle of the state if (form.canBundleState() && form.getSendBundle()) { parts.add( buildFakeFilePart("form_data[att_state]", form.getBundledStateName(), form.getBundledState())); } // attach system properties parts.add(buildFakeFilePart("form_data[att_extra]", form.getExtraStateName(), form.getExtraState())); // attach mcidasv.log (if it exists) if (form.canSendLog()) { parts.add(buildRealFilePart("form_data[att_log]", form.getLogPath())); } // attach RESOLV.SRV (if it exists) if (form.canSendResolvSrv()) { parts.add(buildRealFilePart("form_data[att_resolvsrv]", form.getResolvSrvPath())); } // tack on the contents of runMcV.prefs parts.add(buildRealFilePart("form_data[att_prefs]", form.getPrefsPath())); Part[] arr = parts.toArray(new Part[0]); MultipartRequestEntity mpr = new MultipartRequestEntity(arr, method.getParams()); method.setRequestEntity(mpr); return method; }
From source file:greenfoot.export.mygame.MyGameClient.java
public final MyGameClient submit(String hostAddress, String uid, String password, String jarFileName, File sourceFile, File screenshotFile, int width, int height, ScenarioInfo info) throws UnknownHostException, IOException { String gameName = info.getTitle(); String shortDescription = info.getShortDescription(); String longDescription = info.getLongDescription(); String updateDescription = info.getUpdateDescription(); String gameUrl = info.getUrl(); HttpClient httpClient = getHttpClient(); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(20 * 1000); // 20s timeout // Authenticate user and initiate session PostMethod postMethod = new PostMethod(hostAddress + "account/authenticate"); postMethod.addParameter("user[username]", uid); postMethod.addParameter("user[password]", password); int response = httpClient.executeMethod(postMethod); if (response == 407 && listener != null) { // proxy auth required String[] authDetails = listener.needProxyAuth(); if (authDetails != null) { String proxyHost = httpClient.getHostConfiguration().getProxyHost(); int proxyPort = httpClient.getHostConfiguration().getProxyPort(); AuthScope authScope = new AuthScope(proxyHost, proxyPort); Credentials proxyCreds = new UsernamePasswordCredentials(authDetails[0], authDetails[1]); httpClient.getState().setProxyCredentials(authScope, proxyCreds); // Now retry: response = httpClient.executeMethod(postMethod); }/*from ww w .j a v a 2 s .c om*/ } if (response > 400) { error(Config.getString("export.publish.errorResponse") + " - " + response); return this; } // Check authentication result if (!handleResponse(postMethod)) { return this; } // Send the scenario and associated info List<String> tagsList = info.getTags(); boolean hasSource = sourceFile != null; //determining the number of parts to send through //use a temporary map holder Map<String, String> partsMap = new HashMap<String, String>(); if (info.isUpdate()) { partsMap.put("scenario[update_description]", updateDescription); } else { partsMap.put("scenario[long_description]", longDescription); partsMap.put("scenario[short_description]", shortDescription); } int size = partsMap.size(); if (screenshotFile != null) { size = size + 1; } //base number of parts is 6 int counter = 6; Part[] parts = new Part[counter + size + tagsList.size() + (hasSource ? 1 : 0)]; parts[0] = new StringPart("scenario[title]", gameName, "UTF-8"); parts[1] = new StringPart("scenario[main_class]", "greenfoot.export.GreenfootScenarioViewer", "UTF-8"); parts[2] = new StringPart("scenario[width]", "" + width, "UTF-8"); parts[3] = new StringPart("scenario[height]", "" + height, "UTF-8"); parts[4] = new StringPart("scenario[url]", gameUrl, "UTF-8"); parts[5] = new ProgressTrackingPart("scenario[uploaded_data]", new File(jarFileName), this); Iterator<String> mapIterator = partsMap.keySet().iterator(); String key = ""; String obj = ""; while (mapIterator.hasNext()) { key = mapIterator.next().toString(); obj = partsMap.get(key).toString(); parts[counter] = new StringPart(key, obj, "UTF-8"); counter = counter + 1; } if (hasSource) { parts[counter] = new ProgressTrackingPart("scenario[source_data]", sourceFile, this); counter = counter + 1; } if (screenshotFile != null) { parts[counter] = new ProgressTrackingPart("scenario[screenshot_data]", screenshotFile, this); counter = counter + 1; } int tagNum = 0; for (Iterator<String> i = tagsList.iterator(); i.hasNext();) { parts[counter] = new StringPart("scenario[tag" + tagNum++ + "]", i.next()); counter = counter + 1; } postMethod = new PostMethod(hostAddress + "upload-scenario"); postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams())); response = httpClient.executeMethod(postMethod); if (response > 400) { error(Config.getString("export.publish.errorResponse") + " - " + response); return this; } if (!handleResponse(postMethod)) { return this; } // Done. listener.uploadComplete(new PublishEvent(PublishEvent.STATUS)); return this; }
From source file:com.dtolabs.client.utils.WebserviceHttpClientChannel.java
/** * Returns the RequestEntity for the Post method request. If a file upload is included, it will return a * MultipartRequestEntity with the file as one part. otherwise, null is returned. *///from w ww . j a v a 2s . c om protected RequestEntity getRequestEntity(final PostMethod method) { if (uploadFile != null) { logger.debug("attempting to upload file with colony request"); try { final Part[] parts = new Part[] { new FilePart( null != getFileparam() ? getFileparam() : "uploadFile", uploadFile.getName(), uploadFile) }; return new MultipartRequestEntity(parts, method.getParams()); } catch (FileNotFoundException e) { throw new CoreException( "Could not upload file in request to server: " + uploadFile.getAbsolutePath(), e); } } else { return null; } }
From source file:com.apatar.ui.JFeatureRequestHelpDialog.java
private void addListeners() { sendButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { PostMethod filePost = new PostMethod(getUrl()); // filePost.getParameters().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true); try { if (!CoreUtils.validEmail(emailField.getText())) { JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "E-mail address is invalid! Please, write a valid e-mail."); return; }//from w w w. j av a2s .c om Part[] parts; parts = new Part[4]; parts[0] = new StringPart("FeatureRequest", text.getText()); parts[1] = new StringPart("FirstName", firstNameField.getText()); parts[2] = new StringPart("LastName", lastNameField.getText()); parts[3] = new StringPart("Email", emailField.getText()); 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) JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "Upload failed, response=" + HttpStatus.getStatusText(status)); else { JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "Your message has been sent. Thank you!"); dispose(); } } catch (Exception ex) { ex.printStackTrace(); } finally { filePost.releaseConnection(); } } }); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { dispose(); } }); }
From source file:com.zimbra.qa.unittest.TestFileUpload.java
@Test public void testMissingCsrfAdminUpload() throws Exception { SoapHttpTransport transport = new SoapHttpTransport(TestUtil.getAdminSoapUrl()); com.zimbra.soap.admin.message.AuthRequest req = new com.zimbra.soap.admin.message.AuthRequest( LC.zimbra_ldap_user.value(), LC.zimbra_ldap_password.value()); req.setCsrfSupported(true);//from w w w . j av a 2s.c om Element response = transport.invoke(JaxbUtil.jaxbToElement(req, SoapProtocol.SoapJS.getFactory())); com.zimbra.soap.admin.message.AuthResponse authResp = JaxbUtil.elementToJaxb(response); String authToken = authResp.getAuthToken(); int port = 7071; try { port = Provisioning.getInstance().getLocalServer().getIntAttr(Provisioning.A_zimbraAdminPort, 0); } catch (ServiceException e) { ZimbraLog.test.error("Unable to get admin SOAP port", e); } String Url = "https://localhost:" + port + ADMIN_UPLOAD_URL; PostMethod post = new PostMethod(Url); FilePart part = new FilePart(FILE_NAME, new ByteArrayPartSource(FILE_NAME, "some file content".getBytes())); String contentType = "application/x-msdownload"; part.setContentType(contentType); HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient(); HttpState state = new HttpState(); state.addCookie(new org.apache.commons.httpclient.Cookie("localhost", ZimbraCookie.authTokenCookieName(true), authToken, "/", null, false)); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); client.setState(state); post.setRequestEntity(new MultipartRequestEntity(new Part[] { part }, post.getParams())); int statusCode = HttpClientUtil.executeMethod(client, post); assertEquals("This request should succeed. Getting status code " + statusCode, HttpStatus.SC_OK, statusCode); String resp = post.getResponseBodyAsString(); assertNotNull("Response should not be empty", resp); assertTrue("Incorrect HTML response", resp.contains(RESP_STR)); }
From source file:info.magnolia.cms.filters.MultipartRequestFilterTempFileDeletionTest.java
private MultipartRequestEntity newMultipartRequestEntity() throws Exception { PostMethod method = new PostMethod(); Part[] parts = { new StringPart("param1", "value1", "UTF-8"), new StringPart("param2", "", "UTF-8"), new StringPart("param3", "value3a", "UTF-8"), new StringPart("param3", "value3b", "UTF-8"), new FilePart("document", testFile, "text/xml", "UTF-8") }; return new MultipartRequestEntity(parts, method.getParams()); }
From source file:mesquite.tol.lib.BaseHttpRequestMaker.java
public static byte[] doMultipartPost(String url, Map stringParams, Map fileParams) { PostMethod filePost = new PostMethod(url); Part[] parts = new Part[stringParams.size() + fileParams.size()]; int i = 0;//from ww w. ja va2 s . c om if (stringParams != null) { for (Iterator iter = stringParams.keySet().iterator(); iter.hasNext();) { String nextKey = (String) iter.next(); String nextValue = stringParams.get(nextKey).toString(); parts[i++] = new StringPart(nextKey, nextValue); } } if (fileParams != null) { for (Iterator iter = fileParams.keySet().iterator(); iter.hasNext();) { String nextKey = (String) iter.next(); File nextValue = (File) fileParams.get(nextKey); try { parts[i++] = new FilePart(nextKey, nextValue); } catch (FileNotFoundException e) { e.printStackTrace(); } } } /*System.out.println("going to post multipart to url: " + url + " with parts: " + parts); for (int j = 0; j < parts.length; j++) { Part part = parts[j]; System.out.println("current part is: " + part); }*/ filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); //System.out.println("just set request entity"); return executePost(filePost); }