List of usage examples for org.apache.http.entity FileEntity FileEntity
public FileEntity(File file, ContentType contentType)
From source file:org.openscore.content.httpclient.build.EntityBuilder.java
public HttpEntity buildEntity() { AbstractHttpEntity httpEntity = null; if (!StringUtils.isEmpty(formParams)) { List<? extends NameValuePair> list; list = getNameValuePairs(formParams, !Boolean.parseBoolean(this.formParamsAreURLEncoded), HttpClientInputs.FORM_PARAMS, HttpClientInputs.FORM_PARAMS_ARE_URLENCODED); httpEntity = new UrlEncodedFormEntity(list, contentType.getCharset()); } else if (!StringUtils.isEmpty(body)) { httpEntity = new StringEntity(body, contentType); } else if (!StringUtils.isEmpty(filePath)) { File file = new File(filePath); if (!file.exists()) { throw new IllegalArgumentException( "file set by input '" + HttpClientInputs.SOURCE_FILE + "' does not exist:" + filePath); }//from w ww . j av a 2s . c om httpEntity = new FileEntity(file, contentType); } if (httpEntity != null) { if (!StringUtils.isEmpty(chunkedRequestEntity)) { httpEntity.setChunked(Boolean.parseBoolean(chunkedRequestEntity)); } return httpEntity; } if (!StringUtils.isEmpty(multipartBodies) || !StringUtils.isEmpty(multipartFiles)) { MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); if (!StringUtils.isEmpty(multipartBodies)) { List<? extends NameValuePair> list; list = getNameValuePairs(multipartBodies, !Boolean.parseBoolean(this.multipartValuesAreURLEncoded), HttpClientInputs.MULTIPART_BODIES, HttpClientInputs.MULTIPART_VALUES_ARE_URLENCODED); ContentType bodiesCT = ContentType.parse(multipartBodiesContentType); for (NameValuePair nameValuePair : list) { multipartEntityBuilder.addTextBody(nameValuePair.getName(), nameValuePair.getValue(), bodiesCT); } } if (!StringUtils.isEmpty(multipartFiles)) { List<? extends NameValuePair> list; list = getNameValuePairs(multipartFiles, !Boolean.parseBoolean(this.multipartValuesAreURLEncoded), HttpClientInputs.MULTIPART_FILES, HttpClientInputs.MULTIPART_VALUES_ARE_URLENCODED); ContentType filesCT = ContentType.parse(multipartFilesContentType); for (NameValuePair nameValuePair : list) { File file = new File(nameValuePair.getValue()); multipartEntityBuilder.addBinaryBody(nameValuePair.getName(), file, filesCT, file.getName()); } } return multipartEntityBuilder.build(); } return null; }
From source file:io.cloudslang.content.httpclient.build.EntityBuilder.java
public HttpEntity buildEntity() { AbstractHttpEntity httpEntity = null; if (!StringUtils.isEmpty(formParams)) { List<? extends NameValuePair> list; list = getNameValuePairs(formParams, !Boolean.parseBoolean(this.formParamsAreURLEncoded), HttpClientInputs.FORM_PARAMS, HttpClientInputs.FORM_PARAMS_ARE_URLENCODED); Charset charset = contentType != null ? contentType.getCharset() : null; httpEntity = new UrlEncodedFormEntity(list, charset); } else if (!StringUtils.isEmpty(body)) { httpEntity = new StringEntity(body, contentType); } else if (!StringUtils.isEmpty(filePath)) { File file = new File(filePath); if (!file.exists()) { throw new IllegalArgumentException( "file set by input '" + HttpClientInputs.SOURCE_FILE + "' does not exist:" + filePath); }//from w w w .j av a 2s . co m httpEntity = new FileEntity(file, contentType); } if (httpEntity != null) { if (!StringUtils.isEmpty(chunkedRequestEntity)) { httpEntity.setChunked(Boolean.parseBoolean(chunkedRequestEntity)); } return httpEntity; } if (!StringUtils.isEmpty(multipartBodies) || !StringUtils.isEmpty(multipartFiles)) { MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); if (!StringUtils.isEmpty(multipartBodies)) { List<? extends NameValuePair> list; list = getNameValuePairs(multipartBodies, !Boolean.parseBoolean(this.multipartValuesAreURLEncoded), HttpClientInputs.MULTIPART_BODIES, HttpClientInputs.MULTIPART_VALUES_ARE_URLENCODED); ContentType bodiesCT = ContentType.parse(multipartBodiesContentType); for (NameValuePair nameValuePair : list) { multipartEntityBuilder.addTextBody(nameValuePair.getName(), nameValuePair.getValue(), bodiesCT); } } if (!StringUtils.isEmpty(multipartFiles)) { List<? extends NameValuePair> list; list = getNameValuePairs(multipartFiles, !Boolean.parseBoolean(this.multipartValuesAreURLEncoded), HttpClientInputs.MULTIPART_FILES, HttpClientInputs.MULTIPART_VALUES_ARE_URLENCODED); ContentType filesCT = ContentType.parse(multipartFilesContentType); for (NameValuePair nameValuePair : list) { File file = new File(nameValuePair.getValue()); multipartEntityBuilder.addBinaryBody(nameValuePair.getName(), file, filesCT, file.getName()); } } return multipartEntityBuilder.build(); } return null; }
From source file:com.hoccer.tools.HttpHelper.java
public static HttpResponse putFile(String pUri, File pFile, String pContentType, String pAccept) throws IOException, HttpClientException, HttpServerException { HttpPut put = new HttpPut(pUri); FileEntity entity = new FileEntity(pFile, pContentType); put.setEntity(entity);// w w w . j a v a 2 s. c o m put.addHeader("Content-Type", pContentType); put.addHeader("Accept", pAccept); return executeHTTPMethod(put, PUT_TIMEOUT); }
From source file:code.google.restclient.client.HitterClient.java
private HttpEntity getStringOrFileEntity(String body) throws RCException { if (body == null) body = ""; HttpEntity reqEntity = null;/*from w ww. ja v a2 s . co m*/ if (body.startsWith("@")) { String path = Pattern.compile("^@").matcher(body).replaceAll(""); String mimeType = MimeTypeUtil.getMimeType(path); // TODO not specifying charset as part of mime type i.e. "text/plain" and not "text/plain; charset=UTF-8" reqEntity = new FileEntity(new File(path), mimeType); // second argument is contentType e.g. "text/plain; charset=\"UTF-8\""); } else { try { reqEntity = new StringEntity(body, RCConstants.DEFAULT_CHARSET); } catch (UnsupportedEncodingException e) { throw new RCException( "getStringOrFileEntity(): Could not prepare string post entity due to unsupported encoding", e); } } return reqEntity; }
From source file:com.servoy.extensions.plugins.http.BaseEntityEnclosingRequest.java
@Override protected HttpEntity buildEntity() throws Exception { HttpEntity entity = null;//from w w w .jav a 2 s .c om if (files.size() == 0) { if (params != null) { entity = new UrlEncodedFormEntity(params, charset); } else if (!Utils.stringIsEmpty(content)) { entity = new StringEntity(content, mimeType, charset); content = null; } } else if (files.size() == 1 && (params == null || params.size() == 0)) { Object f = files.values().iterator().next(); if (f instanceof File) { entity = new FileEntity((File) f, ContentType.create("binary/octet-stream")); //$NON-NLS-1$ } else if (f instanceof JSFile) { entity = new InputStreamEntity(((JSFile) f).getAbstractFile().getInputStream(), ((JSFile) f).js_size(), ContentType.create("binary/octet-stream")); //$NON-NLS-1$ } else { Debug.error("could not add file to post request unknown type: " + f); } } else { entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); // For File parameters for (Entry<Pair<String, String>, Object> e : files.entrySet()) { Object file = e.getValue(); if (file instanceof File) { ((MultipartEntity) entity).addPart(e.getKey().getLeft(), new FileBody((File) file)); } else if (file instanceof JSFile) { ((MultipartEntity) entity).addPart(e.getKey().getLeft(), new ByteArrayBody( Utils.getBytesFromInputStream( ((JSFile) file).getAbstractFile().getInputStream()), "binary/octet-stream", ((JSFile) file).js_getName())); } else { Debug.error("could not add file to post request unknown type: " + file); } } // add the parameters if (params != null) { Iterator<NameValuePair> it = params.iterator(); while (it.hasNext()) { NameValuePair nvp = it.next(); // For usual String parameters ((MultipartEntity) entity).addPart(nvp.getName(), new StringBody(nvp.getValue(), "text/plain", Charset.forName(charset))); } } } // entity may have been set already, see PutRequest.js_setFile return entity; }
From source file:com.googlecode.osde.internal.igoogle.IgHostingUtil.java
/** * Uploads a file to iGoogle.//from ww w . j av a2s . c o m * * @throws IgException */ public static void uploadFile(IgCredentials igCredentials, String sourceFileRootPath, String sourceFileRelativePath, String hostingFolder) throws IgException { // Prepare HttpPost. String httpPostUrl = URL_IG_GADGETS_FILE + igCredentials.getPublicId() + hostingFolder + sourceFileRelativePath + "?et=" + igCredentials.getEditToken(); logger.fine("httpPostUrl: " + httpPostUrl); HttpPost httpPost = new HttpPost(httpPostUrl); File sourceFile = new File(sourceFileRootPath, sourceFileRelativePath); String httpContentType = isTextExtensionForGadgetFile(sourceFileRelativePath) ? HTTP_PLAIN_TEXT_TYPE : HTTP.DEFAULT_CONTENT_TYPE; httpPost.setHeader(HTTP.CONTENT_TYPE, httpContentType); FileEntity fileEntity = new FileEntity(sourceFile, httpContentType); logger.fine("fileEntity length: " + fileEntity.getContentLength()); httpPost.setEntity(fileEntity); // Add cookie headers. Cookie PREF must be placed before SID. httpPost.addHeader(IgHttpUtil.HTTP_HEADER_COOKIE, "PREF=" + igCredentials.getPref()); httpPost.addHeader(IgHttpUtil.HTTP_HEADER_COOKIE, "SID=" + igCredentials.getSid()); // Execute request. HttpClient httpClient = new DefaultHttpClient(); HttpResponse httpResponse; try { httpResponse = httpClient.execute(httpPost); } catch (ClientProtocolException e) { throw new IgException(e); } catch (IOException e) { throw new IgException(e); } // Verify if the file is created. StatusLine statusLine = httpResponse.getStatusLine(); logger.fine("statusLine: " + statusLine); if (HttpStatus.SC_CREATED != statusLine.getStatusCode()) { String response = IgHttpUtil.retrieveHttpResponseAsString(httpClient, httpPost, httpResponse); throw new IgException("Failed file-upload with status line: " + statusLine.toString() + ",\nand response:\n" + response); } }
From source file:com.google.resting.method.post.PostServiceContext.java
private HttpEntity setFileEntity(File file, ContentType contentType, EncodingTypes encoding) { FileEntity entity = null;//w ww .j a v a2 s. c om try { entity = new FileEntity(file, contentType.getName()); if (encoding != null) entity.setContentEncoding(encoding.getName()); } catch (Exception e) { e.printStackTrace(); } return entity; }
From source file:com.joyent.manta.client.multipart.AbstractMultipartManager.java
@Override public PART uploadPart(final UPLOAD upload, final int partNumber, final File file) throws IOException { validatePartNumber(partNumber);//w w w . j a va2s.c o m Validate.notNull(file, "File must not be null"); if (!file.exists()) { String msg = String.format("File doesn't exist: %s", file.getPath()); throw new FileNotFoundException(msg); } if (!file.canRead()) { String msg = String.format("Can't access file for read: %s", file.getPath()); throw new IOException(msg); } HttpEntity entity = new FileEntity(file, ContentType.APPLICATION_OCTET_STREAM); return uploadPart(upload, partNumber, entity, null); }
From source file:com.longle1.facedetection.TimedAsyncHttpResponseHandler.java
public void executePut(String putURL, RequestParams params, String filename) { try {//from w w w . j a v a2s.c om AsyncHttpClient client = new AsyncHttpClient(); FileEntity fe = null; fe = new FileEntity(new File(filename), "audio/wav"); // Add SSL KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(mContext.getResources().openRawResource(R.raw.truststore), "changeit".toCharArray()); SSLSocketFactory sf = new SSLSocketFactory(trustStore); client.setSSLSocketFactory(sf); client.setTimeout(30000); client.put(null, putURL + "?" + params.toString(), fe, null, this); } catch (Exception e) { e.printStackTrace(); } Log.i("executePut", "done"); }
From source file:org.apache.tuscany.sca.binding.atom.MediaCollectionTestCase.java
@Test public void testMediaEntryPost() throws Exception { // Pseudo Code (see APP (http://tools.ietf.org/html/rfc5023#section-9.6) // Post request // POST /edit/ HTTP/1.1 // Host: media.example.org // Content-Type: image/png // Slug: The Beach // Content-Length: nnn // ...binary data... // Testing of entry creation String receiptName = "Auto Repair Bill"; String fileName = "target/test-classes/ReceiptToms.gif"; File input = new File(fileName); boolean exists = input.exists(); Assert.assertTrue(exists);/*from w w w . ja v a 2 s.c o m*/ // Prepare HTTP post // PostMethod post = new PostMethod( colUri.toString() ); HttpPost post = new HttpPost(providerURI); post.addHeader("Content-Type", "image/gif"); post.addHeader("Title", "Title " + receiptName + ""); post.addHeader("Slug", "Slug " + receiptName + ""); post.setEntity(new FileEntity(input, "image/gif")); // Get HTTP client org.apache.http.client.HttpClient httpclient = new HttpClientFactory().createHttpClient(); try { // Execute request HttpResponse response = httpclient.execute(post); int result = response.getStatusLine().getStatusCode(); // Pseudo Code (see APP (http://tools.ietf.org/html/rfc5023#section-9.6) // Post response // Tuscany responds with proper media links. Note that the media is // stored in a different location than the media information which is // stored in the Atom feed. // HTTP/1.1 201 Created // Display status code // System.out.println("Response status code: " + result + ", status text=" + post.getStatusText() ); Assert.assertEquals(201, result); // Display response // System.out.println("Response body: "); // System.out.println(post.getResponseBodyAsString()); // Warning: BodyAsString recommends BodyAsStream // Location: http://example.org/media/edit/the_beach.atom (REQUIRED) // System.out.println( "Response Location=" + response.getFirstHeader( "Location" ).getValue() + "." ); Header header = response.getFirstHeader("Location"); Assert.assertNotNull(header); Assert.assertNotNull(header.getValue()); // ContentLocation: http://example.org/media/edit/the_beach.jpg (REQUIRED) // System.out.println( "Response Content-Location=" + response.getFirstHeader( "Content-Location" ).getValue() ); header = response.getFirstHeader("Content-Location"); Assert.assertNotNull(header); Assert.assertNotNull(header.getValue()); // Content-Type: application/atom+xml;type=entry;charset="utf-8" // System.out.println( "Response Content-Type=" + response.getFirstHeader( "Content-Type" ).getValue()); header = response.getFirstHeader("Content-Type"); Assert.assertNotNull(header); Assert.assertNotNull(header.getValue()); // Content-Length: nnn (OPTIONAL) // System.out.println( "Response Content-Length=" + response.getFirstHeader( "Content-Length" ).getValue() ); header = response.getFirstHeader("Content-Length"); Assert.assertNotNull(header); Assert.assertNotNull(header.getValue()); // <?xml version="1.0"?> // <entry xmlns="http://www.w3.org/2005/Atom"> // <title>The Beach</title> (REQUIRED) // <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id> (REQUIRED) // <updated>2005-10-07T17:17:08Z</updated> // <author><name>Daffy</name></author> // <summary type="text" /> (REQUIRED, OPTIONAL to populate // <content type="image/png" src="http://media.example.org/the_beach.png"/> // <link rel="edit-media" href="http://media.example.org/edit/the_beach.png" /> // <link rel="edit" href="http://example.org/media/edit/the_beach.atom" /> // </entry> Document<Entry> document = abderaParser.parse(response.getEntity().getContent()); Entry entry = document.getRoot(); String title = entry.getTitle(); // System.out.println( "mediaPost entry.title=" + title ); Assert.assertNotNull(title); IRI id = entry.getId(); // System.out.println( "mediaPost entry.id=" + id ); Assert.assertNotNull(id); mediaId = id.toString(); Assert.assertNotNull(mediaId); // Save for put/update request Date updated = entry.getUpdated(); // System.out.println( "mediaPost entry.updated=" + updated); Assert.assertNotNull(updated); String summary = entry.getSummary(); // System.out.println( "mediaPost entry.summary=" + summary); Assert.assertNotNull(summary); IRI contentSrc = entry.getContentSrc(); // System.out.println( "mediaPost entry.content.src=" + contentSrc + ", type=" + entry.getContentType()); Assert.assertNotNull(contentSrc); Link editLink = entry.getEditLink(); // System.out.println( "mediaPost entry.editLink" + " rel=" + editLink.getRel() + ", href=" + editLink.getHref() ); Assert.assertNotNull(editLink); Assert.assertNotNull(editLink.getRel()); Assert.assertNotNull(editLink.getHref()); Link editMediaLink = entry.getEditMediaLink(); // System.out.println( "mediaPost entry.editMediaLink" + " rel=" + editMediaLink.getRel() + ", href=" + editMediaLink.getHref() ); Assert.assertNotNull(editMediaLink); Assert.assertNotNull(editMediaLink.getRel()); Assert.assertNotNull(editMediaLink.getHref()); } finally { // Release current connection to the connection pool once you are done // post.releaseConnection(); } }