List of usage examples for org.apache.commons.httpclient.methods.multipart MultipartRequestEntity MultipartRequestEntity
public MultipartRequestEntity(Part[] paramArrayOfPart, HttpMethodParams paramHttpMethodParams)
From source file:net.morphbank.webclient.PostXML.java
public void post(String strURL, String strXMLFilename) throws Exception { File input = new File(strXMLFilename); // Prepare HTTP post PostMethod post = new PostMethod(strURL); // Request content will be retrieved directly // from the input stream Part[] parts = { Part[] parts = { new FilePart("uploadFile", strXMLFilename, input) }; RequestEntity entity = new MultipartRequestEntity(parts, post.getParams()); // RequestEntity entity = new FileRequestEntity(input, // "text/xml;charset=utf-8"); post.setRequestEntity(entity);/*from w w w .ja va 2 s .c o m*/ // Get HTTP client HttpClient httpclient = new HttpClient(); // Execute request try { System.out.println("Trying post"); int result = httpclient.executeMethod(post); // Display status code System.out.println("Response status code: " + result); // Display response System.out.println("Response body: "); InputStream response = post.getResponseBodyAsStream(); //int j = response.read(); System.out.write(j); for (int i = response.read(); i != -1; i = response.read()) { System.out.write(i); } //System.out.flush(); } finally { // Release current connection to the connection pool once you are // done post.releaseConnection(); } }
From source file:edu.unc.lib.dl.cdr.sword.server.test.DepositClientsByHand.java
@Test public void testUpload() throws Exception { String user = ""; String password = ""; String pid = "uuid:c9aba0a2-12e9-4767-822e-b285a37b07d7"; String payloadMimeType = "text/xml"; String payloadPath = "src/test/resources/dcDocument.xml"; String metadataPath = "src/test/resources/atompubMODS.xml"; String depositPath = "https://localhost:444/services/sword/collection/"; String testSlug = "ingesttestslug"; HttpClient client = HttpClientUtil.getAuthenticatedClient(depositPath + pid, user, password); client.getParams().setAuthenticationPreemptive(true); PostMethod post = new PostMethod(depositPath + pid); File payload = new File(payloadPath); File atom = new File(metadataPath); FilePart payloadPart = new FilePart("payload", payload); payloadPart.setContentType(payloadMimeType); payloadPart.setTransferEncoding("binary"); Part[] parts = { payloadPart, new FilePart("atom", atom, "application/atom+xml", "utf-8") }; MultipartRequestEntity mpEntity = new MultipartRequestEntity(parts, post.getParams()); String boundary = mpEntity.getContentType(); boundary = boundary.substring(boundary.indexOf("boundary=") + 9); Header header = new Header("Content-type", "multipart/related; type=application/atom+xml; boundary=" + boundary); post.addRequestHeader(header);/*from w w w . j a v a 2 s.c o m*/ Header slug = new Header("Slug", testSlug); post.addRequestHeader(slug); post.setRequestEntity(mpEntity); LOG.debug("" + client.executeMethod(post)); }
From source file:net.sf.j2ep.test.PostTest.java
public void beginSendMultipart(WebRequest theRequest) { theRequest.setURL("localhost:8080", "/test", "/POST/multipart.jsp", null, null); theRequest.addParameter("tmp", "", WebRequest.POST_METHOD); try {/*from w w w . ja v a2 s . c om*/ PostMethod post = new PostMethod(); FilePart filePart = new FilePart("theFile", new File("WEB-INF/classes/net/sf/j2ep/test/POSTdata")); StringPart stringPart = new StringPart("testParam", "123456"); Part[] parts = new Part[2]; parts[0] = stringPart; parts[1] = filePart; MultipartRequestEntity reqEntitiy = new MultipartRequestEntity(parts, post.getParams()); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); reqEntitiy.writeRequest(outStream); theRequest.setUserData(new ByteArrayInputStream(outStream.toByteArray())); theRequest.addHeader("content-type", reqEntitiy.getContentType()); } catch (FileNotFoundException e) { fail("File was not found " + e.getMessage()); } catch (IOException e) { fail("IOException"); e.printStackTrace(); } }
From source file:de.michaeltamm.W3cMarkupValidator.java
/** * Validates the given <code>html</code>. * * @param html a complete HTML document//from ww w. j av a 2s . c o m */ public W3cMarkupValidationResult validate(String html) { if (_httpClient == null) { final MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); _httpClient = new HttpClient(connectionManager); } final PostMethod postMethod = new PostMethod(_checkUrl); final Part[] data = { // The HTML to validate ... new StringPart("fragment", html, "UTF-8"), new StringPart("prefill", "0", "UTF-8"), new StringPart("doctype", "Inline", "UTF-8"), new StringPart("prefill_doctype", "html401", "UTF-8"), // List Messages Sequentially | Group Error Messages by Type ... new StringPart("group", "0", "UTF-8"), // Show source ... new StringPart("ss", "1", "UTF-8"), // Verbose Output ... new StringPart("verbose", "1", "UTF-8"), }; postMethod.setRequestEntity(new MultipartRequestEntity(data, postMethod.getParams())); try { final int status = _httpClient.executeMethod(postMethod); if (status != 200) { throw new RuntimeException(_checkUrl + " responded with " + status); } final String pathPrefix = _checkUrl.substring(0, _checkUrl.lastIndexOf('/') + 1); final String resultPage = getResponseBody(postMethod).replace("\"./", "\"" + pathPrefix) .replace("src=\"images/", "src=\"" + pathPrefix + "images/") .replace("<script type=\"text/javascript\" src=\"loadexplanation.js\">", "<script type=\"text/javascript\" src=\"" + pathPrefix + "loadexplanation.js\">"); return new W3cMarkupValidationResult(resultPage); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } finally { postMethod.releaseConnection(); } }
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()); }/* w w w.ja v a2 s .co m*/ 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:ca.uvic.chisel.logging.eclipse.internal.network.LogUploadRunnable.java
public void run(IProgressMonitor sendMonitor) throws InterruptedException, InvocationTargetException { File[] filesToUpload = log.getCategory().getFilesToUpload(); sendMonitor.beginTask("Uploading Log " + log.getCategory().getName(), filesToUpload.length); LoggingCategory category = log.getCategory(); IMemento memento = category.getMemento(); for (File file : filesToUpload) { if (sendMonitor.isCanceled()) { throw new InterruptedException(); }// w w w.j ava 2 s. c o m PostMethod post = new PostMethod(category.getURL().toString()); try { Part[] parts = { new StringPart("KIND", "workbench-log"), new StringPart("CATEGORY", category.getCategoryID()), new StringPart("USER", WorkbenchLoggingPlugin.getDefault().getLocalUser()), new FilePart("WorkbenchLogger", file.getName(), file, "application/zip", null) }; post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); HttpClient client = new HttpClient(); int status = client.executeMethod(post); String resp = getData(post.getResponseBodyAsStream()); if (status != 200 || !resp.startsWith("Status: 200 Success")) { IOException ex = new IOException(resp); throw (ex); } memento.putString("lastUpload", file.getName()); file.delete(); } catch (IOException e) { throw new InvocationTargetException(e); } finally { sendMonitor.worked(1); } } sendMonitor.done(); }
From source file:demo.jaxrs.search.client.Client.java
private static void uploadToCatalog(final String url, final HttpClient httpClient, final String filename) throws IOException, HttpException { System.out.println("Sent HTTP POST request to upload the file into catalog: " + filename); final PostMethod post = new PostMethod(url); final Part[] parts = { new FilePart(filename, new ByteArrayPartSource(filename, IOUtils.readBytesFromStream(Client.class.getResourceAsStream("/" + filename)))) }; post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); try {//from ww w. j a v a2 s . c o m int status = httpClient.executeMethod(post); if (status == 201) { System.out.println(post.getResponseHeader("Location")); } else if (status == 409) { System.out.println("Document already exists: " + filename); } } finally { post.releaseConnection(); } }
From source file:com.nokia.carbide.internal.bugreport.model.Communication.java
/** * Sends given fields as a bug_report to the server provided by product. * @param fields values which are sent to the server * @param product product provides e.g. server URL * @return bug_id of the added bug_entry * @throws RuntimeException if an error occurred. Error can be either some communication error * or error message provided by the server (e.g. invalid password) *//*from w w w . ja va 2 s . co m*/ public static String sendBugReport(Hashtable<String, String> fields, IProduct product) throws RuntimeException { // Nothing to send if (fields == null || fields.size() < 1) { throw new RuntimeException(Messages.getString("Communication.NothingToSend")); //$NON-NLS-1$ } String bugNumber = ""; //$NON-NLS-1$ String url = product.getUrl(); if (url.startsWith("https")) { //$NON-NLS-1$ // we'll support HTTPS with trusted (i.e. signed) certificates // Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol"); //$NON-NLS-1$ //$NON-NLS-2$ } PostMethod filePost = new PostMethod(url); Part[] parts = new Part[fields.size()]; int i = 0; Iterator<Map.Entry<String, String>> it = fields.entrySet().iterator(); // create parts while (it.hasNext()) { Map.Entry<String, String> productField = it.next(); // attachment field if (productField.getKey() == FieldsHandler.FIELD_ATTACHMENT) { File f = new File(productField.getValue()); try { parts[i] = new FilePart(FieldsHandler.FIELD_DATA, f); } catch (FileNotFoundException e) { e.printStackTrace(); parts[i] = new StringPart(FieldsHandler.FIELD_DATA, Messages.getString("Communication.NotFound")); //$NON-NLS-1$ } // string field } else { parts[i] = new StringPart(productField.getKey(), productField.getValue()); } i++; } filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(8000); setProxyData(client, filePost); int status = 0; String receivedData = ""; //$NON-NLS-1$ try { status = client.executeMethod(filePost); receivedData = filePost.getResponseBodyAsString(1024 * 1024); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } finally { filePost.releaseConnection(); } // HTTP status codes: 2xx = Success if (status >= 200 && status < 300) { // some error occurred in the server side (e.g. invalid password) if (receivedData.contains(FieldsHandler.TAG_RESPONSE_ERROR) && receivedData.contains(FieldsHandler.TAG_RESPONSE_ERROR_CLOSE)) { int beginIndex = receivedData.indexOf(FieldsHandler.TAG_RESPONSE_ERROR) + FieldsHandler.TAG_RESPONSE_ERROR.length(); int endIndex = receivedData.indexOf(FieldsHandler.TAG_RESPONSE_ERROR_CLOSE); String error = receivedData.substring(beginIndex, endIndex); error = error.trim(); throw new RuntimeException(error); // bug_entry was added successfully to database, read the bug_number } else if (receivedData.contains(FieldsHandler.TAG_RESPONSE_BUG_ID) && receivedData.contains(FieldsHandler.TAG_RESPONSE_BUG_ID_CLOSE)) { int beginIndex = receivedData.indexOf(FieldsHandler.TAG_RESPONSE_BUG_ID) + FieldsHandler.TAG_RESPONSE_BUG_ID.length(); int endIndex = receivedData.indexOf(FieldsHandler.TAG_RESPONSE_BUG_ID_CLOSE); bugNumber = receivedData.substring(beginIndex, endIndex); bugNumber = bugNumber.trim(); // some unknown error } else { throw new RuntimeException(Messages.getString("Communication.UnknownError")); //$NON-NLS-1$ } // some HTTP error (status code other than 2xx) } else { String error = Messages.getString("Communication.HttpError") + status; //$NON-NLS-1$ throw new RuntimeException(error); } return bugNumber; }
From source file:edu.harvard.iq.dvn.core.web.dvnremote.ICPSRauth.java
public String obtainAuthCookie(String username, String password, String fileDownloadUrl) { PostMethod loginPostMethod = null;/* w w w.j a v a 2 s .c o m*/ if (username == null || password == null) { return null; } int status = 0; String icpsrAuthCookie = null; try { dbgLog.fine("entering ICPSR auth;"); HttpClient httpclient = getClient(); loginPostMethod = new PostMethod(icpsrLoginUrl); Part[] parts = { new StringPart("email", username), new StringPart("password", password), new StringPart("path", "ICPSR"), new StringPart("request_uri", fileDownloadUrl) }; loginPostMethod.setRequestEntity(new MultipartRequestEntity(parts, loginPostMethod.getParams())); status = httpclient.executeMethod(loginPostMethod); dbgLog.fine("executed POST method; status=" + status); if (status != 200) { loginPostMethod.releaseConnection(); return null; } String regexpTicketCookie = "(Ticket=[^;]*)"; Pattern patternTicketCookie = Pattern.compile(regexpTicketCookie); for (int i = 0; i < loginPostMethod.getResponseHeaders().length; i++) { String headerName = loginPostMethod.getResponseHeaders()[i].getName(); if (headerName.equalsIgnoreCase("set-cookie")) { String cookieHeader = loginPostMethod.getResponseHeaders()[i].getValue(); Matcher cookieMatcher = patternTicketCookie.matcher(cookieHeader); if (cookieMatcher.find()) { icpsrAuthCookie = cookieMatcher.group(1); dbgLog.fine("detected ICPSR ticket cookie: " + cookieHeader); } } } loginPostMethod.releaseConnection(); return icpsrAuthCookie; } catch (IOException ex) { dbgLog.info("ICPSR auth: caught IO exception."); ex.printStackTrace(); if (loginPostMethod != null) { loginPostMethod.releaseConnection(); } return null; } }
From source file:edu.indiana.dlib.avalon.HydrantWorkflowListener.java
private void pingHydrant(String pid, long workflowId) { logger.trace("Starting to ping Hydrant: " + pid + " " + workflowId); try {//w w w . ja va 2 s. c o m String url = UrlSupport.concat(new String[] { hydrantUrl, "master_files", pid }); MultiThreadedHttpConnectionManager mgr = new MultiThreadedHttpConnectionManager(); HttpClient client = new HttpClient(mgr); PutMethod put = new PutMethod(url); Part[] parts = { new StringPart("workflow_id", String.valueOf(workflowId)), }; put.setRequestEntity(new MultipartRequestEntity(parts, put.getParams())); logger.trace("About to ping Hydrant"); int status = client.executeMethod(put); logger.debug("Got status: " + status); logger.trace("Got response body: " + put.getResponseBodyAsString()); } catch (Exception e) { logger.debug("Exception pinging Hydrant: " + e.getCause(), e); } }