List of usage examples for org.apache.commons.httpclient.methods.multipart MultipartRequestEntity MultipartRequestEntity
public MultipartRequestEntity(Part[] paramArrayOfPart, HttpMethodParams paramHttpMethodParams)
From source file:com.foglyn.fogbugz.Request.java
Document post(String url, List<Part> parts, IProgressMonitor monitor) throws FogBugzException { PostMethod postMethod = new PostMethod(url); // postMethod.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true); postMethod.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[0]), postMethod.getParams())); Document result = request(url, postMethod, monitor, new DocumentResponseProcessor()); if (checkResponseError) { throwExceptionOnError(result);/*from ww w . j a v a2s. c o m*/ } return result; }
From source file:com.intuit.tank.httpclient3.TankHttpClient3.java
@Override public void doPost(BaseRequest request) { try {/* w ww .j a v a2 s . co m*/ PostMethod httppost = new PostMethod(request.getRequestUrl()); String requestBody = request.getBody(); RequestEntity entity = null; if (BaseRequest.CONTENT_TYPE_MULTIPART.equalsIgnoreCase(request.getContentType())) { List<Part> parts = buildParts(request); entity = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), httppost.getParams()); } else { entity = new StringRequestEntity(requestBody, request.getContentType(), request.getContentTypeCharSet()); } httppost.setRequestEntity(entity); sendRequest(request, httppost, requestBody); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
From source file:com.github.maven.plugin.client.impl.GithubClientImpl.java
public void upload(String artifactName, File file, String description, String repositoryUrl) { assertNotNull(artifactName, "artifactName"); assertNotNull(file, "file"); assertNotNull(repositoryUrl, "repositoryUrl"); assertStartsWith(repositoryUrl, GITHUB_REPOSITORY_URL_PREFIX, "repositoryUrl"); PostMethod githubPost = new PostMethod(toRepositoryDownloadUrl(repositoryUrl)); githubPost.setRequestBody(new NameValuePair[] { new NameValuePair("login", login), new NameValuePair("token", token), new NameValuePair("file_name", artifactName), new NameValuePair("file_size", String.valueOf(file.length())), new NameValuePair("description", description == null ? "" : description) }); try {//from w w w.ja v a2s . c o m int response = httpClient.executeMethod(githubPost); if (response == HttpStatus.SC_OK) { ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readValue(githubPost.getResponseBodyAsString(), JsonNode.class); PostMethod s3Post = new PostMethod(GITHUB_S3_URL); Part[] parts = { new StringPart("Filename", artifactName), new StringPart("policy", node.path("policy").getTextValue()), new StringPart("success_action_status", "201"), new StringPart("key", node.path("path").getTextValue()), new StringPart("AWSAccessKeyId", node.path("accesskeyid").getTextValue()), new StringPart("Content-Type", node.path("mime_type").getTextValue()), new StringPart("signature", node.path("signature").getTextValue()), new StringPart("acl", node.path("acl").getTextValue()), new FilePart("file", file) }; MultipartRequestEntity partEntity = new MultipartRequestEntity(parts, s3Post.getParams()); s3Post.setRequestEntity(partEntity); int s3Response = httpClient.executeMethod(s3Post); if (s3Response != HttpStatus.SC_CREATED) { throw new GithubException( "Cannot upload " + file.getName() + " to repository " + repositoryUrl); } s3Post.releaseConnection(); } else if (response == HttpStatus.SC_NOT_FOUND) { throw new GithubRepositoryNotFoundException("Cannot found repository " + repositoryUrl); } else if (response == HttpStatus.SC_UNPROCESSABLE_ENTITY) { throw new GithubArtifactAlreadyExistException( "File " + artifactName + " already exist in " + repositoryUrl + " repository"); } else { throw new GithubException("Error " + HttpStatus.getStatusText(response)); } } catch (IOException e) { throw new GithubException(e); } githubPost.releaseConnection(); }
From source file:fedora.client.FedoraClient.java
/** * Upload the given file to Fedora's upload interface via HTTP POST. * * @return the temporary id which can then be passed to API-M requests as a * URL. It will look like uploaded://123 *///from ww w . j av a 2 s . c o m public String uploadFile(File file) throws IOException { PostMethod post = null; try { // prepare the post method post = new PostMethod(getUploadURL()); post.setDoAuthentication(true); post.getParams().setParameter("Connection", "Keep-Alive"); // chunked encoding is not required by the Fedora server, // but makes uploading very large files possible post.setContentChunked(true); // add the file part Part[] parts = { new FilePart("file", file) }; post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); // execute and get the response int responseCode = getHttpClient().executeMethod(post); String body = null; try { body = post.getResponseBodyAsString(); } catch (Exception e) { LOG.warn("Error reading response body", e); } if (body == null) { body = "[empty response body]"; } body = body.trim(); if (responseCode != HttpStatus.SC_CREATED) { throw new IOException("Upload failed: " + HttpStatus.getStatusText(responseCode) + ": " + replaceNewlines(body, " ")); } else { return replaceNewlines(body, ""); } } finally { if (post != null) { post.releaseConnection(); } } }
From source file:eu.impact_project.iif.t2.client.WorkflowRunnerTest.java
/** * Test of doPost method, of class WorkflowRunner. *//*from ww w . j a va 2s . com*/ @Test public void testDoPostURLFail() throws Exception { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); ServletConfig config = mock(ServletConfig.class); ServletContext context = mock(ServletContext.class); RequestDispatcher dispatcher = mock(RequestDispatcher.class); ServletOutputStream stream = mock(ServletOutputStream.class); HttpSession session = mock(HttpSession.class); when(request.getSession(true)).thenReturn(session); ArrayList<Workflow> flowList = new ArrayList<>(); Workflow flow = new Workflow(); flow.setStringVersion("Esto es una prueba"); flow.setWsdls("<wsdl>http://www.ua.es</wsdl>"); flow.setUrls("http://falsa.es"); ArrayList<WorkflowInput> flowInputs = new ArrayList<>(); WorkflowInput input = new WorkflowInput("pru0Input"); input.setDepth(1); flowInputs.add(input); input = new WorkflowInput("pru1Input"); input.setDepth(0); flowInputs.add(input); flow.setInputs(flowInputs); flowList.add(flow); when(session.getAttribute("workflows")).thenReturn(flowList); when(config.getServletContext()).thenReturn(context); URL url = this.getClass().getResource("/config.properties"); File testFile = new File(url.getFile()); when(context.getRealPath("/")).thenReturn(testFile.getParent() + "/"); Part[] parts = new Part[] { new StringPart("user", "user"), new StringPart("pass", "pass"), new StringPart("workflow0pru0Input", "prueba0"), new StringPart("workflow0pru0Input0", "prueba0.0"), new StringPart("workflow0pru1Input", "prueba1") }; MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, new PostMethod().getParams()); ByteArrayOutputStream requestContent = new ByteArrayOutputStream(); multipartRequestEntity.writeRequest(requestContent); final ByteArrayInputStream inputContent = new ByteArrayInputStream(requestContent.toByteArray()); when(request.getInputStream()).thenReturn(new ServletInputStream() { @Override public int read() throws IOException { return inputContent.read(); } }); when(request.getContentType()).thenReturn(multipartRequestEntity.getContentType()); WorkflowRunner runer = new WorkflowRunner(); try { runer.init(config); runer.doPost(request, response); } catch (ServletException ex) { fail("Should not raise exception " + ex.toString()); } catch (IOException ex) { fail("Should not raise exception " + ex.toString()); } catch (NullPointerException ex) { //ok no funciona el server de taverna } }
From source file:edu.virginia.speclab.juxta.author.view.export.WebServiceClient.java
public String beginExport(final File jxtFile, final String name, final String desc, boolean overwrite) throws IOException { PostMethod post = null;/*from www . j a v a 2 s . com*/ if (overwrite) { post = new PostMethod(this.baseUrl + "/import?overwrite"); } else { post = new PostMethod(this.baseUrl + "/import"); } Part[] parts = { new StringPart("token", this.authToken), new StringPart("setName", name), new StringPart("description", desc), new FilePart("jxtFile", jxtFile) }; post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); execRequest(post); String response = getResponseString(post); post.releaseConnection(); return response; }
From source file:it.eng.spagobi.engines.talend.client.SpagoBITalendEngineClient_0_5_0.java
public boolean deployJob(JobDeploymentDescriptor jobDeploymentDescriptor, File executableJobFiles) throws EngineUnavailableException, AuthenticationFailedException, ServiceInvocationFailedException { HttpClient client;// w ww . ja va 2 s . c o m PostMethod method; File deploymentDescriptorFile; boolean result = false; client = new HttpClient(); method = new PostMethod(getServiceUrl(JOB_UPLOAD_SERVICE)); deploymentDescriptorFile = null; try { deploymentDescriptorFile = File.createTempFile("deploymentDescriptor", ".xml"); //$NON-NLS-1$ //$NON-NLS-2$ FileWriter writer = new FileWriter(deploymentDescriptorFile); writer.write(jobDeploymentDescriptor.toXml()); writer.flush(); writer.close(); Part[] parts = { new FilePart(executableJobFiles.getName(), executableJobFiles), new FilePart("deploymentDescriptor", deploymentDescriptorFile) }; //$NON-NLS-1$ method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); int status = client.executeMethod(method); if (status == HttpStatus.SC_OK) { if (method.getResponseBodyAsString().equalsIgnoreCase("OK")) //$NON-NLS-1$ result = true; } else { throw new ServiceInvocationFailedException( Messages.getString("SpagoBITalendEngineClient_0_5_0.serviceExcFailed") + JOB_UPLOAD_SERVICE, //$NON-NLS-1$ method.getStatusLine().toString(), method.getResponseBodyAsString()); } } catch (HttpException e) { throw new EngineUnavailableException( Messages.getString("SpagoBITalendEngineClient_0_5_0.protocolViolation") + e.getMessage()); //$NON-NLS-1$ } catch (IOException e) { throw new EngineUnavailableException( Messages.getString("SpagoBITalendEngineClient_0_5_0.transportError") + e.getMessage()); //$NON-NLS-1$ } finally { method.releaseConnection(); if (deploymentDescriptorFile != null) deploymentDescriptorFile.delete(); } return result; }
From source file:net.sf.antcontrib.net.httpclient.PostMethodTask.java
protected void configureMethod(HttpMethodBase method) { PostMethod post = (PostMethod) method; if (parts.size() == 1 && !multipart) { Object part = parts.get(0); if (part instanceof FilePartType) { FilePartType filePart = (FilePartType) part; try { stream = new FileInputStream(filePart.getPath().getAbsolutePath()); post.setRequestEntity(new InputStreamRequestEntity(stream, filePart.getPath().length(), filePart.getContentType())); } catch (IOException e) { throw new BuildException(e); }// w w w . j a va2 s. co m } else if (part instanceof TextPartType) { TextPartType textPart = (TextPartType) part; try { post.setRequestEntity(new StringRequestEntity(textPart.getValue(), textPart.getContentType(), textPart.getCharSet())); } catch (UnsupportedEncodingException e) { throw new BuildException(e); } } } else if (!parts.isEmpty()) { Part partArray[] = new Part[parts.size()]; for (int i = 0; i < parts.size(); i++) { Object part = parts.get(i); if (part instanceof FilePartType) { FilePartType filePart = (FilePartType) part; try { partArray[i] = new FilePart(filePart.getPath().getName(), filePart.getPath().getName(), filePart.getPath(), filePart.getContentType(), filePart.getCharSet()); } catch (FileNotFoundException e) { throw new BuildException(e); } } else if (part instanceof TextPartType) { TextPartType textPart = (TextPartType) part; partArray[i] = new StringPart(textPart.getName(), textPart.getValue(), textPart.getCharSet()); ((StringPart) partArray[i]).setContentType(textPart.getContentType()); } } MultipartRequestEntity entity = new MultipartRequestEntity(partArray, post.getParams()); post.setRequestEntity(entity); } }
From source file:com.benfante.jslideshare.SlideShareConnectorImpl.java
public InputStream sendMultiPartMessage(String url, Map<String, String> parameters, Map<String, File> files) throws IOException, SlideShareErrorException { HttpClient client = createHttpClient(); PostMethod method = new PostMethod(url); List<Part> partList = new ArrayList(); partList.add(createStringPart("api_key", this.apiKey)); Date now = new Date(); String ts = Long.toString(now.getTime() / 1000); String hash = DigestUtils.shaHex(this.sharedSecret + ts).toLowerCase(); partList.add(createStringPart("ts", ts)); partList.add(createStringPart("hash", hash)); Iterator<Map.Entry<String, String>> entryIt = parameters.entrySet().iterator(); while (entryIt.hasNext()) { Map.Entry<String, String> entry = entryIt.next(); partList.add(createStringPart(entry.getKey(), entry.getValue())); }// www . j a va 2 s. c o m Iterator<Map.Entry<String, File>> entryFileIt = files.entrySet().iterator(); while (entryFileIt.hasNext()) { Map.Entry<String, File> entry = entryFileIt.next(); partList.add(createFilePart(entry.getKey(), entry.getValue())); } MultipartRequestEntity requestEntity = new MultipartRequestEntity( partList.toArray(new Part[partList.size()]), method.getParams()); method.setRequestEntity(requestEntity); logger.debug("Sending multipart POST message to " + method.getURI().getURI() + " with parts " + partList); int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { logger.debug("Server replied with a " + statusCode + " HTTP status code (" + HttpStatus.getStatusText(statusCode) + ")"); throw new SlideShareErrorException(statusCode, HttpStatus.getStatusText(statusCode)); } if (logger.isDebugEnabled()) { logger.debug(method.getResponseBodyAsString()); } InputStream result = new ByteArrayInputStream(method.getResponseBody()); method.releaseConnection(); return result; }
From source file:PublisherUtil.java
/** * Publishes a list of files and a datasource to the server with basic authentication to the server * /* w w w . j a va2s .c o m*/ * @param publishURL * The URL of the Pentaho server * @param publishPath * The path in the solution to place the files * @param publishFiles * Array of File objects to post to the server * @param dataSource * The datasource to publish to the server * @param publishPassword * The publishing password for the server * @param serverUserid * The userid to authenticate to the server * @param serverPassword * The password to authenticate with the server * @param overwrite * Whether the server should overwrite the file if it exists already * @param mkdirs * Whether the server should create any missing folders on the publish path * @return Server response as a string * @throws Exception */ public static String publish(final String publishURL, final String publishPath, final File publishFiles[], final String publishPassword, final String serverUserid, final String serverPassword, final boolean overwrite, final boolean mkdirs) throws Exception { int status = -1; System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); //$NON-NLS-1$ //$NON-NLS-2$ System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true"); //$NON-NLS-1$ //$NON-NLS-2$ System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire.header", "warn");//$NON-NLS-1$ //$NON-NLS-2$ System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "warn");//$NON-NLS-1$ //$NON-NLS-2$ String fullURL = null; try { fullURL = publishURL + "?publishPath=" + URLEncoder.encode(publishPath, "UTF-8"); } catch (UnsupportedEncodingException e) { fullURL = publishURL + "?publishPath=" + publishPath; System.out.println("Erro de publicao na classe publisher!" + e); // throw new Exception("Erro de publicao na classe publisher!" + e); } if (publishPassword == null) { throw new IllegalArgumentException("PUBLISHERUTIL.ERROR_0001_PUBLISH_PASSWORD_REQUIRED"); //$NON-NLS-1$ // throw new IllegalArgumentException(Messages.getErrorString("PUBLISHERUTIL.ERROR_0001_PUBLISH_PASSWORD_REQUIRED")); //$NON-NLS-1$ } fullURL += "&publishKey=" + PublisherUtil.getPasswordKey(publishPassword); //$NON-NLS-1$ fullURL += "&overwrite=" + overwrite; //$NON-NLS-1$ fullURL += "&mkdirs=" + mkdirs; //$NON-NLS-1$ PostMethod filePost = new PostMethod(fullURL); Part[] parts = new Part[publishFiles.length]; for (int i = 0; i < publishFiles.length; i++) { try { File file = publishFiles[i]; FileInputStream in = new FileInputStream(file); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); String reportNameEncoded = (URLEncoder.encode(file.getName(), "UTF-8")); ByteArrayPartSource source = new ByteArrayPartSource(reportNameEncoded, out.toByteArray()); parts[i] = new FilePart(reportNameEncoded, source, FilePart.DEFAULT_CONTENT_TYPE, "UTF-8"); } catch (Exception e) { PublisherUtil.logger.error(null, e); throw new Exception("Erro de publicao na classe publisher!" + e); } } filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); try { if ((serverUserid != null) && (serverUserid.length() > 0) && (serverPassword != null) && (serverPassword.length() > 0)) { Credentials creds = new UsernamePasswordCredentials(serverUserid, serverPassword); client.getState().setCredentials(AuthScope.ANY, creds); client.getParams().setAuthenticationPreemptive(true); } status = client.executeMethod(filePost); if (status == HttpStatus.SC_OK) { String postResult = filePost.getResponseBodyAsString(); if (postResult != null) { try { return postResult.trim(); // +" - "+Integer.parseInt(postResult.trim()); } catch (NumberFormatException e) { PublisherUtil.logger.error(null, e); // throw new Exception("Erro de publicao na classe publisher!" + e + " " +PublisherUtil.FILE_ADD_INVALID_USER_CREDENTIALS); return "" + PublisherUtil.FILE_ADD_INVALID_USER_CREDENTIALS; } } } else if (status == HttpStatus.SC_UNAUTHORIZED) { return "" + PublisherUtil.FILE_ADD_INVALID_USER_CREDENTIALS; } } catch (HttpException e) { PublisherUtil.logger.error(null, e); // throw new Exception("Erro de publicao na classe publisher!" + e ); } catch (IOException e) { PublisherUtil.logger.error(null, e); // throw new Exception("Erro de publicao na classe publisher!" + e ); } // return Messages.getString("REPOSITORYFILEPUBLISHER.USER_PUBLISHER_FAILED"); //$NON-NLS-1$ return "" + PublisherUtil.FILE_ADD_FAILED; }