List of usage examples for org.apache.http.entity.mime MultipartEntity addPart
public void addPart(final String name, final ContentBody contentBody)
From source file:com.klinker.android.twitter.utils.api_helper.TwitPicHelper.java
private TwitPicStatus uploadToTwitPic() { try {/*from www . j a v a2s . com*/ HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(POST_URL); post.addHeader("X-Auth-Service-Provider", SERVICE_PROVIDER); post.addHeader("X-Verify-Credentials-Authorization", getAuthrityHeader(twitter)); if (file == null) { // only the input stream was sent, so we need to convert it to a file Log.v("talon_twitpic", "converting to file from input stream"); String filePath = saveStreamTemp(stream); file = new File(filePath); } else { Log.v("talon_twitpic", "already have the file, going right to send it"); } MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("key", new StringBody(TWITPIC_API_KEY)); entity.addPart("media", new FileBody(file)); entity.addPart("message", new StringBody(message)); Log.v("talon_twitpic", "uploading now"); post.setEntity(entity); HttpResponse response = client.execute(post); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line; String url = ""; StringBuilder builder = new StringBuilder(); while ((line = rd.readLine()) != null) { Log.v("talon_twitpic", line); builder.append(line); } try { // there is only going to be one thing returned ever JSONObject jsonObject = new JSONObject(builder.toString()); url = jsonObject.getString("url"); } catch (Exception e) { e.printStackTrace(); } Log.v("talon_twitpic", "url: " + url); Log.v("talon_twitpic", "message: " + message); return new TwitPicStatus(message, url); } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:org.ubicompforall.BusTUC.Speech.HTTP.java
public void sendPostByteArray(byte[] buf) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://vm-6114.idi.ntnu.no:1337/SpeechServer/sst"); try {/*w w w . jav a 2s.c o m*/ MultipartEntity entity = new MultipartEntity(); // entity.addPart("speechinput", new FileBody((buf, // "application/zip")); entity.addPart("speechinput", new ByteArrayBody(buf, "Jun.wav")); httppost.setEntity(entity); String response = EntityUtils.toString(httpclient.execute(httppost).getEntity(), "UTF-8"); System.out.println("RESPONSE: " + response); } catch (ClientProtocolException e) { } catch (IOException e) { } }
From source file:org.fcrepo.integration.api.FedoraDatastreamsIT.java
License:asdf
@Test public void testRetrieveMultipartDatastreams() throws Exception { final HttpPost objMethod = postObjMethod("FedoraDatastreamsTest9"); assertEquals(201, getStatus(objMethod)); final HttpPost post = new HttpPost(serverAddress + "objects/FedoraDatastreamsTest9/datastreams/"); final MultipartEntity multiPartEntity = new MultipartEntity(); multiPartEntity.addPart("ds1", new StringBody("asdfg")); multiPartEntity.addPart("ds2", new StringBody("qwerty")); post.setEntity(multiPartEntity);/*ww w . jav a2 s. co m*/ final HttpResponse postResponse = client.execute(post); assertEquals(201, postResponse.getStatusLine().getStatusCode()); // TODO: we should actually evaluate the multipart response for the // things we're expecting final HttpGet getDSesMethod = new HttpGet( serverAddress + "objects/FedoraDatastreamsTest9/datastreams/__content__"); final HttpResponse response = client.execute(getDSesMethod); assertEquals(200, response.getStatusLine().getStatusCode()); final String content = EntityUtils.toString(response.getEntity()); assertTrue("Didn't find the first datastream!", compile("asdfg", DOTALL).matcher(content).find()); assertTrue("Didn't find the second datastream!", compile("qwerty", DOTALL).matcher(content).find()); }
From source file:org.fcrepo.integration.api.FedoraDatastreamsIT.java
License:asdf
@Test public void testRetrieveFIlteredMultipartDatastreams() throws Exception { final HttpPost objMethod = postObjMethod("FedoraDatastreamsTest10"); assertEquals(201, getStatus(objMethod)); final HttpPost post = new HttpPost(serverAddress + "objects/FedoraDatastreamsTest10/datastreams/"); final MultipartEntity multiPartEntity = new MultipartEntity(); multiPartEntity.addPart("ds1", new StringBody("asdfg")); multiPartEntity.addPart("ds2", new StringBody("qwerty")); post.setEntity(multiPartEntity);/*from w w w .j ava2 s.c om*/ final HttpResponse postResponse = client.execute(post); assertEquals(201, postResponse.getStatusLine().getStatusCode()); // TODO: we should actually evaluate the multipart response for the // things we're expecting final HttpGet getDSesMethod = new HttpGet( serverAddress + "objects/FedoraDatastreamsTest10/datastreams/__content__?dsid=ds1"); final HttpResponse response = client.execute(getDSesMethod); assertEquals(200, response.getStatusLine().getStatusCode()); final String content = EntityUtils.toString(response.getEntity()); assertTrue("Didn't find the first datastream!", compile("asdfg", DOTALL).matcher(content).find()); assertFalse("Didn't expect to find the second datastream!", compile("qwerty", DOTALL).matcher(content).find()); }
From source file:eu.nubomedia.nubomedia_kurento_health_communicator_android.kc_and_communicator.services.AuthClientService.java
public boolean createUser(String accountId, UserCreate user, String contentPath) throws TransportException, InvalidDataException, NotFoundException, KurentoCommandException { log.debug("Create user {}", user.getName()); JSONObject object = new JSONObject(); try {//from w ww .ja v a2s . c o m object.put(JsonKeys.PASSWORD, user.getPassword()); object.put(JsonKeys.NAME, user.getName()); object.put(JsonKeys.SURNAME, user.getSurname()); object.put(JsonKeys.PHONE, user.getPhone()); object.put(JsonKeys.EMAIL, user.getEmail()); object.put(JsonKeys.PHONE_REGION, ConstantKeys.ES); } catch (JSONException e) { log.debug("Error creating object"); return false; } String json = object.toString(); String charset = HTTP.UTF_8; MultipartEntity mpEntity = new MultipartEntity(); try { mpEntity.addPart(USER_PART_NAME, new StringBody(json, HttpManager.CONTENT_TYPE_APPLICATION_JSON, Charset.forName(charset))); } catch (UnsupportedEncodingException e) { String msg = "Cannot use " + charset + "as entity"; log.error(msg, e); throw new TransportException(msg); } File content = new File(contentPath); mpEntity.addPart(PICTURE_PART_NAME, new FileBody(content, ConstantKeys.TYPE_IMAGE)); HttpResp<Void> resp = HttpManager.sendPostVoid(context, context.getString(R.string.url_create_user, accountId), mpEntity); return resp.getCode() == HttpStatus.SC_CREATED; }
From source file:org.bonitasoft.engine.api.HTTPServerAPI.java
final HttpEntity buildEntity(final Map<String, Serializable> options, final List<String> classNameParameters, final Object[] parametersValues, final XStream xstream) throws UnsupportedEncodingException, IOException { final HttpEntity httpEntity; /*/*from w w w.j a v a 2s.c om*/ * if we have a business archive we use multipart to have the business archive attached as a binary content (it can be big) */ if (classNameParameters.contains(BusinessArchive.class.getName()) || classNameParameters.contains(byte[].class.getName())) { final List<Object> bytearrayParameters = new ArrayList<Object>(); final MultipartEntity entity = new MultipartEntity(null, null, UTF8); entity.addPart(OPTIONS, new StringBody(toXML(options, xstream), UTF8)); entity.addPart(CLASS_NAME_PARAMETERS, new StringBody(toXML(classNameParameters, xstream), UTF8)); for (int i = 0; i < parametersValues.length; i++) { final Object parameterValue = parametersValues[i]; if (parameterValue instanceof BusinessArchive || parameterValue instanceof byte[]) { parametersValues[i] = BYTE_ARRAY; bytearrayParameters.add(parameterValue); } } entity.addPart(PARAMETERS_VALUES, new StringBody(toXML(parametersValues, xstream), UTF8)); int i = 0; for (final Object object : bytearrayParameters) { entity.addPart(BINARY_PARAMETER + i, new ByteArrayBody(serialize(object), BINARY_PARAMETER + i)); i++; } httpEntity = entity; } else { final List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair(OPTIONS, toXML(options, xstream))); nvps.add(new BasicNameValuePair(CLASS_NAME_PARAMETERS, toXML(classNameParameters, xstream))); nvps.add(new BasicNameValuePair(PARAMETERS_VALUES, toXML(parametersValues, xstream))); httpEntity = new UrlEncodedFormEntity(nvps, UTF_8); } return httpEntity; }
From source file:com.tek271.reverseProxy.servlet.ProxyFilter.java
private static MultipartEntity getMultipartEntity(HttpServletRequest request) { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); Enumeration<String> en = request.getParameterNames(); while (en.hasMoreElements()) { String name = en.nextElement(); String value = request.getParameter(name); try {//from w w w .j av a2 s. c o m if (name.equals("file")) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(10000000);// 10 Mo List items = upload.parseRequest(request); Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); File file = new File(item.getName()); FileOutputStream fos = new FileOutputStream(file); fos.write(item.get()); fos.flush(); fos.close(); entity.addPart(name, new FileBody(file, "application/zip")); } } else { entity.addPart(name, new StringBody(value.toString(), "text/plain", Charset.forName("UTF-8"))); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (FileUploadException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (FileNotFoundException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } return entity; }
From source file:me.ziccard.secureit.async.AudioRecorderTask.java
@Override public void run() { MicrophoneTaskFactory.pauseSampling(); while (MicrophoneTaskFactory.isSampling()) { try {/* ww w. ja v a 2 s . c om*/ Thread.sleep(50); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } recording = true; final MediaRecorder recorder = new MediaRecorder(); ContentValues values = new ContentValues(3); values.put(MediaStore.MediaColumns.TITLE, filename); recorder.setAudioSource(MediaRecorder.AudioSource.MIC); recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC); String audioPath = Environment.getExternalStorageDirectory().getPath() + filename + ".m4a"; recorder.setOutputFile(audioPath); try { recorder.prepare(); } catch (Exception e) { e.printStackTrace(); return; } Log.i("AudioRecorderTask", "Start recording"); recorder.start(); try { Thread.sleep(prefs.getAudioLenght()); } catch (InterruptedException e) { e.printStackTrace(); } recorder.stop(); Log.i("AudioRecorderTask", "Stopped recording"); recorder.release(); recording = false; MicrophoneTaskFactory.restartSampling(); /* * Uploading the audio */ Log.i("AudioRecorderTask", "Trying to upload"); HttpClient httpclient = new DefaultHttpClient(); HttpPost request = new HttpPost(Remote.HOST + Remote.PHONES + "/" + phoneId + Remote.UPLOAD_AUDIO); Log.i("AudioRecorderTask", "URI: " + Remote.HOST + Remote.PHONES + "/" + phoneId + Remote.UPLOAD_AUDIO); /* * Getting the audio from the file system */ MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); File audio = new File(audioPath); reqEntity.addPart("audio", new FileBody(audio, "audio/mp3")); request.setEntity(reqEntity); /* * Authentication token */ request.setHeader("access_token", accessToken); try { HttpResponse response = httpclient.execute(request); BufferedReader reader = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), "UTF-8")); StringBuilder builder = new StringBuilder(); for (String line = null; (line = reader.readLine()) != null;) { builder.append(line).append("\n"); } Log.i("AudioRecorderTask", "Response:\n" + builder.toString()); if (response.getStatusLine().getStatusCode() != 200) { Log.i("AudioRecorderTask", "Error uploading audio: " + audioPath); throw new HttpException(); } } catch (Exception e) { Log.e("DataUploaderTask", "Error uploading audio: " + audioPath); } }
From source file:org.fcrepo.integration.api.FedoraDatastreamsIT.java
License:asdf
@Test public void testModifyMultipleDatastreams() throws Exception { final HttpPost objMethod = postObjMethod("FedoraDatastreamsTest8"); assertEquals(201, getStatus(objMethod)); final HttpPost createDSVOIDMethod = postDSMethod("FedoraDatastreamsTest8", "ds_void", "marbles for everyone"); assertEquals(201, getStatus(createDSVOIDMethod)); final HttpPost post = new HttpPost( serverAddress + "objects/FedoraDatastreamsTest8/datastreams?delete=ds_void"); final MultipartEntity multiPartEntity = new MultipartEntity(); multiPartEntity.addPart("ds1", new StringBody("asdfg")); multiPartEntity.addPart("ds2", new StringBody("qwerty")); post.setEntity(multiPartEntity);/*from w w w . java2 s. c om*/ final HttpResponse postResponse = client.execute(post); assertEquals(201, postResponse.getStatusLine().getStatusCode()); final HttpGet getDSesMethod = new HttpGet(serverAddress + "objects/FedoraDatastreamsTest8/datastreams"); final HttpResponse response = client.execute(getDSesMethod); assertEquals(200, response.getStatusLine().getStatusCode()); final String content = EntityUtils.toString(response.getEntity()); assertTrue("Didn't find the first datastream!", compile("dsid=\"ds1\"", DOTALL).matcher(content).find()); assertTrue("Didn't find the second datastream!", compile("dsid=\"ds2\"", DOTALL).matcher(content).find()); assertFalse("Found the deleted datastream!", compile("dsid=\"ds_void\"", DOTALL).matcher(content).find()); }