List of usage examples for org.apache.http.entity.mime.content FileBody FileBody
public FileBody(final File file, final String mimeType)
From source file:fm.smart.r1.activity.CreateSoundActivity.java
public CreateSoundResult createSound(File file, String media_entity, String author, String author_url, String attribution_license_id, String id) { String http_response = ""; int status_code = 0; HttpClient client = null;/*from w w w . j a v a2s. c o m*/ String type = "sentence"; String location = ""; try { client = new DefaultHttpClient(); if (sound_type.equals(Integer.toString(R.id.cue_sound))) { type = "item"; } HttpPost post = new HttpPost("http://api.smart.fm/" + type + "s/" + id + "/sounds"); String auth = Main.username(this) + ":" + Main.password(this); byte[] bytes = auth.getBytes(); post.setHeader("Authorization", "Basic " + new String(Base64.encodeBase64(bytes))); post.setHeader("Host", "api.smart.fm"); FileBody bin = new FileBody(file, "audio/amr"); StringBody media_entity_part = new StringBody(media_entity); StringBody author_part = new StringBody(author); StringBody author_url_part = new StringBody(author_url); StringBody attribution_license_id_part = new StringBody(attribution_license_id); StringBody id_part = new StringBody(id); StringBody api_key_part = new StringBody(Main.API_KEY); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("sound[file]", bin); reqEntity.addPart("media_entity", media_entity_part); reqEntity.addPart("author", author_part); reqEntity.addPart("author_url", author_url_part); reqEntity.addPart("attribution_license_id", attribution_license_id_part); reqEntity.addPart(type + "_id", id_part); reqEntity.addPart("api_key", api_key_part); post.setEntity(reqEntity); Header[] array = post.getAllHeaders(); for (int i = 0; i < array.length; i++) { Log.d("DEBUG", array[i].toString()); } Log.d("CreateSoundActivity", "executing request " + post.getRequestLine()); HttpResponse response = client.execute(post); status_code = response.getStatusLine().getStatusCode(); HttpEntity resEntity = response.getEntity(); Log.d("CreateSoundActivity", "----------------------------------------"); Log.d("CreateSoundActivity", response.getStatusLine().toString()); array = response.getAllHeaders(); String header; for (int i = 0; i < array.length; i++) { header = array[i].toString(); if (header.equals("Location")) { location = header; } Log.d("CreateSoundActivity", header); } if (resEntity != null) { Log.d("CreateSoundActivity", "Response content length: " + resEntity.getContentLength()); Log.d("CreateSoundActivity", "Chunked?: " + resEntity.isChunked()); } long length = response.getEntity().getContentLength(); byte[] response_bytes = new byte[(int) length]; response.getEntity().getContent().read(response_bytes); Log.d("CreateSoundActivity", new String(response_bytes)); http_response = new String(response_bytes); if (resEntity != null) { resEntity.consumeContent(); } // HttpEntity entity = response1.getEntity(); } catch (IOException e) { /* Reset to Default image on any error. */ e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return new CreateSoundResult(status_code, http_response, location); }
From source file:com.mobile.natal.natalchart.NetworkUtilities.java
/** * Sends a {@link MultipartEntity} post with text and image files. * * @param url the url to which to POST to. * @param user the user or <code>null</code>. * @param pwd the password or <code>null</code>. * @param stringsMap the {@link HashMap} containing the key and string pairs to send. * @param filesMap the {@link HashMap} containing the key and image file paths * (jpg, png supported) pairs to send. * @throws Exception if something goes wrong. *///from w w w . ja v a 2 s .co m public static void sentMultiPartPost(String url, String user, String pwd, HashMap<String, String> stringsMap, HashMap<String, File> filesMap) throws Exception { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpPost httppost = new HttpPost(url); if (user != null && pwd != null && user.trim().length() > 0 && pwd.trim().length() > 0) { String ret = getB64Auth(user, pwd); httppost.setHeader("Authorization", ret); } MultipartEntity mpEntity = new MultipartEntity(); Set<Entry<String, String>> stringsEntrySet = stringsMap.entrySet(); for (Entry<String, String> stringEntry : stringsEntrySet) { ContentBody cbProperties = new StringBody(stringEntry.getValue()); mpEntity.addPart(stringEntry.getKey(), cbProperties); } Set<Entry<String, File>> filesEntrySet = filesMap.entrySet(); for (Entry<String, File> filesEntry : filesEntrySet) { String propName = filesEntry.getKey(); File file = filesEntry.getValue(); if (file.exists()) { String ext = file.getName().toLowerCase().endsWith("jpg") ? "jpeg" : "png"; ContentBody cbFile = new FileBody(file, "image/" + ext); mpEntity.addPart(propName, cbFile); } } httppost.setEntity(mpEntity); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { resEntity.consumeContent(); } httpclient.getConnectionManager().shutdown(); }
From source file:fm.smart.r1.CreateSoundActivity.java
public CreateSoundResult createSound(File file, String media_entity, String author, String author_url, String attribution_license_id, String item_id, String id, String to_record) { String http_response = ""; int status_code = 0; HttpClient client = null;//from ww w .jav a 2s. co m String type = "sentence"; String location = ""; try { client = new DefaultHttpClient(); if (sound_type.equals(Integer.toString(R.id.cue_sound))) { type = "item"; } HttpPost post = new HttpPost("http://api.smart.fm/" + type + "s/" + id + "/sounds.json"); String auth = LoginActivity.username(this) + ":" + LoginActivity.password(this); byte[] bytes = auth.getBytes(); post.setHeader("Authorization", "Basic " + new String(Base64.encodeBase64(bytes))); post.setHeader("Host", "api.smart.fm"); FileBody bin = new FileBody(file, "audio/amr"); StringBody media_entity_part = new StringBody(media_entity); StringBody author_part = new StringBody(author); StringBody author_url_part = new StringBody(author_url); StringBody attribution_license_id_part = new StringBody(attribution_license_id); StringBody id_part = new StringBody(id); StringBody api_key_part = new StringBody(Main.API_KEY); StringBody version_part = new StringBody("2"); StringBody text_part = new StringBody(to_record); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("sound[file]", bin); reqEntity.addPart("media_entity", media_entity_part); reqEntity.addPart("author", author_part); reqEntity.addPart("author_url", author_url_part); reqEntity.addPart("attribution_license_id", attribution_license_id_part); reqEntity.addPart(type + "_id", id_part); reqEntity.addPart("api_key", api_key_part); reqEntity.addPart("text", text_part); reqEntity.addPart("v", version_part); post.setEntity(reqEntity); Header[] array = post.getAllHeaders(); for (int i = 0; i < array.length; i++) { Log.d("DEBUG", array[i].toString()); } Log.d("CreateSoundActivity", "executing request " + post.getRequestLine()); HttpResponse response = client.execute(post); status_code = response.getStatusLine().getStatusCode(); HttpEntity resEntity = response.getEntity(); Log.d("CreateSoundActivity", "----------------------------------------"); Log.d("CreateSoundActivity", response.getStatusLine().toString()); array = response.getAllHeaders(); String header; for (int i = 0; i < array.length; i++) { header = array[i].toString(); if (header.equals("Location")) { location = header; } Log.d("CreateSoundActivity", header); } if (resEntity != null) { Log.d("CreateSoundActivity", "Response content length: " + resEntity.getContentLength()); Log.d("CreateSoundActivity", "Chunked?: " + resEntity.isChunked()); } long length = response.getEntity().getContentLength(); byte[] response_bytes = new byte[(int) length]; response.getEntity().getContent().read(response_bytes); Log.d("CreateSoundActivity", new String(response_bytes)); http_response = new String(response_bytes); if (resEntity != null) { resEntity.consumeContent(); } // HttpEntity entity = response1.getEntity(); } catch (IOException e) { /* Reset to Default image on any error. */ e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return new CreateSoundResult(status_code, http_response, location); }
From source file:org.apache.camel.component.cxf.jaxrs.simplebinding.CxfRsConsumerSimpleBindingTest.java
@Test public void testMultipartPostWithParametersAndPayload() throws Exception { HttpPost post = new HttpPost( "http://localhost:" + PORT_PATH + "/rest/customerservice/customers/multipart/123?query=abcd"); MultipartEntity multipart = new MultipartEntity(HttpMultipartMode.STRICT); multipart.addPart("part1", new FileBody( new File(this.getClass().getClassLoader().getResource("java.jpg").toURI()), "java.jpg")); multipart.addPart("part2", new FileBody( new File(this.getClass().getClassLoader().getResource("java.jpg").toURI()), "java.jpg")); StringWriter sw = new StringWriter(); jaxb.createMarshaller().marshal(new Customer(123, "Raul"), sw); multipart.addPart("body", new StringBody(sw.toString(), "text/xml", Charset.forName("UTF-8"))); post.setEntity(multipart);//from ww w . ja va2 s . c o m HttpResponse response = httpclient.execute(post); assertEquals(200, response.getStatusLine().getStatusCode()); }
From source file:com.gargoylesoftware.htmlunit.html.HtmlFileInputTest.java
/** * Test HttpClient for uploading a file with non-ASCII name, if it works it means HttpClient has fixed its bug. * * Test for http://issues.apache.org/jira/browse/HTTPCLIENT-293, * which is related to http://sourceforge.net/p/htmlunit/bugs/535/ * * @throws Exception if the test fails//from w ww.j a v a 2 s .c o m */ @Test public void uploadFileWithNonASCIIName_HttpClient() throws Exception { final String filename = "\u6A94\u6848\uD30C\uC77C\u30D5\u30A1\u30A4\u30EB\u0645\u0644\u0641.txt"; final String path = getClass().getClassLoader().getResource(filename).toExternalForm(); final File file = new File(new URI(path)); assertTrue(file.exists()); final Map<String, Class<? extends Servlet>> servlets = new HashMap<>(); servlets.put("/upload2", Upload2Servlet.class); startWebServer("./", null, servlets); final HttpPost filePost = new HttpPost("http://localhost:" + PORT + "/upload2"); final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE).setCharset(Charset.forName("UTF-8")); builder.addPart("myInput", new FileBody(file, ContentType.APPLICATION_OCTET_STREAM)); filePost.setEntity(builder.build()); final HttpClientBuilder clientBuilder = HttpClientBuilder.create(); final HttpResponse httpResponse = clientBuilder.build().execute(filePost); InputStream content = null; try { content = httpResponse.getEntity().getContent(); final String response = new String(IOUtils.toByteArray(content)); //this is the value with ASCII encoding assertFalse("3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 2E 74 78 74 <br>myInput".equals(response)); } finally { IOUtils.closeQuietly(content); } }
From source file:org.wso2.am.integration.tests.publisher.APIM614AddDocumentationToAnAPIWithDocTypeSampleAndSDKThroughPublisherRestAPITestCase.java
@Test(groups = { "wso2.am" }, description = "Add Documentation To An API With Type support forum And" + " Source File through the publisher rest API ", dependsOnMethods = "testAddDocumentToAnAPIPublicToFile") public void testAddDocumentToAnAPISupportToFile() throws Exception { String fileNameAPIM626 = "APIM626.txt"; String docName = "APIM626PublisherTestHowTo-File-summary"; String docType = "support forum"; String sourceType = "file"; String summary = "Testing"; String mimeType = "text/plain"; String docUrl = "http://"; String filePathAPIM626 = TestConfigurationProvider.getResourceLocation() + File.separator + "artifacts" + File.separator + "AM" + File.separator + "lifecycletest" + File.separator + fileNameAPIM626; String addDocUrl = publisherUrls.getWebAppURLHttp() + "publisher/site/blocks/documentation/ajax/docs.jag"; //Send Http Post request to add a new file HttpPost httppost = new HttpPost(addDocUrl); File file = new File(filePathAPIM626); FileBody fileBody = new FileBody(file, "text/plain"); //Create multipart entity to upload file as multipart file MultipartEntity multipartEntity = new MultipartEntity(); multipartEntity.addPart("docLocation", fileBody); multipartEntity.addPart("mode", new StringBody("")); multipartEntity.addPart("docName", new StringBody(docName)); multipartEntity.addPart("docUrl", new StringBody(docUrl)); multipartEntity.addPart("sourceType", new StringBody(sourceType)); multipartEntity.addPart("summary", new StringBody(summary)); multipartEntity.addPart("docType", new StringBody(docType)); multipartEntity.addPart("version", new StringBody(apiVersion)); multipartEntity.addPart("apiName", new StringBody(apiName)); multipartEntity.addPart("action", new StringBody("addDocumentation")); multipartEntity.addPart("provider", new StringBody(apiProvider)); multipartEntity.addPart("mimeType", new StringBody(mimeType)); multipartEntity.addPart("optionsRadios", new StringBody(docType)); multipartEntity.addPart("optionsRadios1", new StringBody(sourceType)); multipartEntity.addPart("optionsRadios1", new StringBody(sourceType)); httppost.setEntity(multipartEntity); //Upload created file and validate HttpResponse response = httpClient.execute(httppost); HttpEntity entity = response.getEntity(); JSONObject jsonObject1 = new JSONObject(EntityUtils.toString(entity)); assertFalse(jsonObject1.getBoolean("error"), "Error when adding files to the API "); }
From source file:com.gsbabil.antitaintdroid.UtilityFunctions.java
public String httpFileUpload(String filePath) { String sResponse = ""; HttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpPost httppost = new HttpPost(MyApp.HTTP_OCR_URL); MultipartEntity mpEntity = new MultipartEntity(); File file = new File(filePath); ContentBody cbFile = new FileBody(file, "image/png"); mpEntity.addPart("image", cbFile); httppost.setEntity(mpEntity);/*from w w w. java 2 s . c o m*/ HttpResponse response = null; try { response = httpClient.execute(httppost); BufferedReader reader = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), "UTF-8")); String line; while ((line = reader.readLine()) != null) { if (sResponse != null) { sResponse = sResponse.trim() + "\n" + line.trim(); } else { sResponse = line; } } Log.i(MyApp.TAG, sResponse); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { EntityUtils.consume(resEntity); } httpClient.getConnectionManager().shutdown(); } catch (Throwable e) { Log.i(MyApp.TAG, e.getMessage().toString()); } return sResponse.trim(); }
From source file:org.apache.camel.component.cxf.jaxrs.simplebinding.CxfRsConsumerSimpleBindingTest.java
@Test public void testMultipartPostWithoutParameters() throws Exception { HttpPost post = new HttpPost("http://localhost:" + PORT_PATH + "/rest/customerservice/customers/multipart"); MultipartEntity multipart = new MultipartEntity(HttpMultipartMode.STRICT); multipart.addPart("part1", new FileBody( new File(this.getClass().getClassLoader().getResource("java.jpg").toURI()), "java.jpg")); multipart.addPart("part2", new FileBody( new File(this.getClass().getClassLoader().getResource("java.jpg").toURI()), "java.jpg")); StringWriter sw = new StringWriter(); jaxb.createMarshaller().marshal(new Customer(123, "Raul"), sw); multipart.addPart("body", new StringBody(sw.toString(), "text/xml", Charset.forName("UTF-8"))); post.setEntity(multipart);//from w w w . j a v a 2s . c om HttpResponse response = httpclient.execute(post); assertEquals(200, response.getStatusLine().getStatusCode()); }