List of usage examples for org.apache.http.entity.mime.content FileBody FileBody
public FileBody(final File file, final String mimeType)
From source file:com.ibm.streamsx.topology.internal.context.AnalyticsServiceStreamsContext.java
private BigInteger postJob(CloseableHttpClient httpClient, JSONObject credentials, File bundle, JSONObject submitConfig) throws ClientProtocolException, IOException { String url = getSubmitURL(credentials, bundle); HttpPost postJobWithConfig = new HttpPost(url); postJobWithConfig.addHeader("accept", ContentType.APPLICATION_JSON.getMimeType()); FileBody bundleBody = new FileBody(bundle, ContentType.APPLICATION_OCTET_STREAM); StringBody configBody = new StringBody(submitConfig.serialize(), ContentType.APPLICATION_JSON); HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bundleBody) .addPart("json", configBody).build(); postJobWithConfig.setEntity(reqEntity); JSONObject jsonResponse = getJsonResponse(httpClient, postJobWithConfig); Topology.STREAMS_LOGGER.info("Streaming Analytics Service submit job response:" + jsonResponse.serialize()); Object jobId = jsonResponse.get("jobId"); if (jobId == null) return BigInteger.valueOf(-1); return new BigInteger(jobId.toString()); }
From source file:com.iia.giveastick.util.RestClient.java
private HttpEntity buildMultipartEntity(JSONObject jsonParams) { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); try {//from w ww. j ava 2 s. com String path = jsonParams.getString("file"); if (debugWeb && GiveastickApplication.DEBUG) { Log.d(TAG, "key : file value :" + path); } if (!TextUtils.isEmpty(path)) { // File entry File file = new File(path); FileBody fileBin = new FileBody(file, "application/octet"); entity.addPart("file", fileBin); try { entity.addPart("file", new StringBody(path, "text/plain", Charset.forName(HTTP.UTF_8))); } catch (UnsupportedEncodingException e) { e.printStackTrace(); Log.e(TAG, e.getMessage()); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return entity; }
From source file:com.versacomllc.audit.network.sync.SyncAdapter.java
private String uploadFile(String path) { String downloadPath = Constants.FILE_CONTENT_PATH; if (TextUtils.isEmpty(path)) { Log.d(LOG_TAG, "File path is empty."); return null; }//w w w . j a v a2s .c om HttpClient httpclient = new DefaultHttpClient(); try { File file = new File(path); HttpPost httppost = new HttpPost(FILE_UPLOAD_PATH); String mimeType = URLConnection.guessContentTypeFromName(path); FileBody bin = new FileBody(file, mimeType); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart(file.getName(), bin); httppost.setEntity(reqEntity); Log.i(TAG, "executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { Log.i(TAG, "Response content length: " + resEntity.getContentLength()); } downloadPath = downloadPath + file.getName(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) { } } return downloadPath; }
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 {// ww w . j a va 2 s. co 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.openbmap.soapclient.FileUploader.java
/** * @param file//from ww w . j av a 2 s . c o m * @return */ private boolean performUpload(final String file) { // TODO check network state // @see http://developer.android.com/training/basics/network-ops/connecting.html // Adjust HttpClient parameters final HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. // The default value is zero, that means the timeout is not used. //HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. //HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIMEOUT); final DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters); final HttpPost httppost = new HttpPost(mServer); try { final String authorizationString = "Basic " + Base64.encodeToString((mUser + ":" + mPassword).getBytes(), Base64.NO_WRAP); httppost.setHeader("Authorization", authorizationString); final MultipartEntity entity = new MultipartEntity(); // TODO we don't need passwords for the new service entity.addPart(LOGIN_FIELD, new StringBody(mUser)); entity.addPart(PASSWORD_FIELD, new StringBody(mPassword)); entity.addPart(FILE_FIELD, new FileBody(new File(file), "text/xml")); httppost.setEntity(entity); final HttpResponse response = httpclient.execute(httppost); final int reply = response.getStatusLine().getStatusCode(); if (reply == 200) { Log.i(TAG, "Uploaded " + file + ": Server reply " + reply); } else { Log.w(TAG, "Error while uploading" + file + ": Server reply " + reply); } // everything is ok if we receive HTTP 200 // TODO: redirects (301, 302) are NOT handled here // thus if something changes on the server side we're dead here return (reply == HttpStatus.SC_OK); } catch (final ClientProtocolException e) { Log.e(TAG, e.getMessage()); } catch (final IOException e) { Log.e(TAG, "I/O exception on file " + file); } return false; }
From source file:de.vanita5.twittnuker.util.net.TwidereHttpClientImpl.java
private static HttpEntity getAsEntity(final HttpParameter[] params) throws UnsupportedEncodingException { if (params == null) return null; if (!HttpParameter.containsFile(params)) return new HttpParameterFormEntity(params); final MultipartEntityBuilder me = MultipartEntityBuilder.create(); for (final HttpParameter param : params) { if (param.isFile()) { final ContentType contentType = ContentType.create(param.getContentType()); final ContentBody body; if (param.getFile() != null) { body = new FileBody(param.getFile(), ContentType.create(param.getContentType())); } else { body = new InputStreamBody(param.getFileBody(), contentType, param.getFileName()); }/*from ww w . j av a 2 s . co m*/ me.addPart(param.getName(), body); } else { final ContentType contentType = ContentType.TEXT_PLAIN.withCharset(Consts.UTF_8); final ContentBody body = new StringBody(param.getValue(), contentType); me.addPart(param.getName(), body); } } return me.build(); }
From source file:com.frentix.restapi.RestConnection.java
/** * Attach file to POST request./*ww w . j a v a 2s . co m*/ * * @param post the request * @param filename the filename field * @param file the file * @throws UnsupportedEncodingException */ public void addMultipart(HttpEntityEnclosingRequestBase post, String filename, File file) throws UnsupportedEncodingException { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("filename", new StringBody(filename)); FileBody fileBody = new FileBody(file, "application/octet-stream"); entity.addPart("file", fileBody); post.setEntity(entity); }
From source file:truesculpt.ui.panels.WebFilePanel.java
private void uploadPicture(File imagefile, File zipobjectfile, String uploadURL, String title, String description) throws ParseException, IOException, URISyntaxException { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(uploadURL); httppost.addHeader("title", title); httppost.addHeader("description", description); httppost.addHeader("installationID", UtilsManager.Installation.id(this)); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.STRICT); ContentBody cbImageFile = new FileBody(imagefile, "image/png"); ContentBody cbObjectFile = new FileBody(zipobjectfile, "application/zip"); mpEntity.addPart("imagefile", cbImageFile); mpEntity.addPart("objectfile", cbObjectFile); httppost.setEntity(mpEntity);// w w w. j a v a2s . c o m System.out.println("executing request " + httppost.getRequestLine()); HttpResponse httpResponse = httpclient.execute(httppost); String myHeader = "displayURL"; Header[] headers = httpResponse.getHeaders(myHeader); for (int i = 0; i < headers.length; i++) { Header header = headers[i]; if (header.getName().equals(myHeader)) { String newURL = mStrBaseWebSite + header.getValue(); Log.d("WEB", "Loading web site " + newURL); mWebView.loadUrl(newURL); } } }
From source file:com.glasshack.checkmymath.CheckMyMath.java
public String post(String url, List<NameValuePair> nameValuePairs) { HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpPost httpPost = new HttpPost(url); String readableResponse = null; try {/*from w ww .jav a 2 s .c om*/ MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (int index = 0; index < nameValuePairs.size(); index++) { if (nameValuePairs.get(index).getName().equalsIgnoreCase("file")) { // If the key equals to "file", we use FileBody to transfer the data entity.addPart("file", new FileBody(new File(nameValuePairs.get(index).getValue()), "image/jpeg")); } else { // Normal string data entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue())); } } httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost, localContext); readableResponse = EntityUtils.toString(response.getEntity(), "UTF-8"); Log.e("response", readableResponse); } catch (IOException e) { e.printStackTrace(); } return readableResponse; }
From source file:com.alphabetbloc.accessmrs.utilities.NetworkUtils.java
public static MultipartEntity createMultipartEntity(String path) { // find all files in parent directory File file = new File(path); File[] files = file.getParentFile().listFiles(); if (App.DEBUG) Log.v(TAG, file.getAbsolutePath()); // mime post/* ww w . jav a2 s . c o m*/ MultipartEntity entity = null; if (files != null) { entity = new MultipartEntity(); for (int j = 0; j < files.length; j++) { File f = files[j]; FileBody fb; if (f.getName().endsWith(".xml")) { fb = new FileBody(f, "text/xml"); entity.addPart("xml_submission_file", fb); if (App.DEBUG) Log.v(TAG, "added xml file " + f.getName()); } else if (f.getName().endsWith(".jpg")) { fb = new FileBody(f, "image/jpeg"); entity.addPart(f.getName(), fb); if (App.DEBUG) Log.v(TAG, "added image file " + f.getName()); } else if (f.getName().endsWith(".3gpp")) { fb = new FileBody(f, "audio/3gpp"); entity.addPart(f.getName(), fb); if (App.DEBUG) Log.v(TAG, "added audio file " + f.getName()); } else if (f.getName().endsWith(".3gp")) { fb = new FileBody(f, "video/3gpp"); entity.addPart(f.getName(), fb); if (App.DEBUG) Log.v(TAG, "added video file " + f.getName()); } else if (f.getName().endsWith(".mp4")) { fb = new FileBody(f, "video/mp4"); entity.addPart(f.getName(), fb); if (App.DEBUG) Log.v(TAG, "added video file " + f.getName()); } else { Log.w(TAG, "unsupported file type, not adding file: " + f.getName()); } } } else { if (App.DEBUG) Log.v(TAG, "no files to upload in instance"); } return entity; }