List of usage examples for org.apache.http.entity.mime MultipartEntity MultipartEntity
public MultipartEntity()
From source file:org.gitana.platform.client.support.RemoteImpl.java
@Override public void upload(String uri, byte[] bytes, String mimetype, String filename) throws Exception { String URL = buildURL(uri, false); HttpPost httpPost = new HttpPost(URL); HttpPayload payload = new HttpPayload(); payload.setBytes(bytes);//w w w . j av a 2s . co m payload.setContentType(mimetype); payload.setFilename(filename); payload.setLength(bytes.length); MultipartEntity entity = new MultipartEntity(); entity.addPart(filename, new HttpPayloadContentBody(payload)); httpPost.setEntity(entity); HttpResponse httpResponse = invoker.execute(httpPost); if (!HttpUtil.isOk(httpResponse)) { throw new RuntimeException("Upload failed: " + EntityUtils.toString(httpResponse.getEntity())); } // consume the response fully so that the client connection can be reused EntityUtils.consume(httpResponse.getEntity()); }
From source file:setiquest.renderer.Utils.java
/** * Send a BSON file./* w w w . j a va 2 s .c o m*/ * @param filename the full path to the BSON file. * @param actId the activity Id. * @param obsId the observation Id. * @param pol the POL of thedata. * @param subchannel the subchannel of the data. */ public static String sendBSONFile(String filename, int actId, int obsId, int pol, String subchannel) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(Utils.getSubjectsURL()); Log.log("Sending " + filename + ", Act:" + actId + ", Obs type:" + obsId + ", Pol" + pol + ", subchannel:" + subchannel); FileBody bin = new FileBody(new File(filename)); try { StringBody comment = new StringBody("Filename: " + filename); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file", bin); reqEntity.addPart("type", new StringBody("data/bson")); reqEntity.addPart("subject[activity_id]", new StringBody("" + actId)); reqEntity.addPart("subject[observation_id]", new StringBody("" + obsId)); reqEntity.addPart("subject[pol]", new StringBody("" + pol)); reqEntity.addPart("subject[subchannel]", new StringBody("" + subchannel)); httppost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); Log.log(response.toString()); return response.toString(); /* sendResult = "subject[activity_id]: " + actId + "\n"; sendResult += "subject[observation_id]: " + obsId + "\n"; sendResult += "subject[pol]: " + pol + "\n"; sendResult += "subject[subchannel]: " + subchannel + "\n"; sendResult += response.toString() + "|\n"; */ } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "ERROR"; }
From source file:org.wso2.mdm.qsg.utils.HTTPInvoker.java
public static HTTPResponse uploadFile(String url, String fileName, String fileContentType) { HttpPost post = null;/* w w w .j ava2s.c o m*/ HttpResponse response = null; HTTPResponse httpResponse = new HTTPResponse(); CloseableHttpClient httpclient = null; try { httpclient = (CloseableHttpClient) createHttpClient(); post = new HttpPost(url); File file = new File(fileName); MultipartEntity mpEntity = new MultipartEntity(); ContentBody cbFile = new FileBody(file, fileContentType); mpEntity.addPart("file", cbFile); post.setEntity(mpEntity); post.setHeader(Constants.Header.AUTH, OAUTH_BEARER + oAuthToken); //post.setHeader(Constants.Header.CONTENT_TYPE, "multipart/form-data"); post.setHeader("Accept", Constants.ContentType.APPLICATION_JSON); response = httpclient.execute(post); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } BufferedReader rd = null; try { rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); } catch (IOException e) { e.printStackTrace(); } StringBuffer result = new StringBuffer(); String line = ""; try { while ((line = rd.readLine()) != null) { result.append(line); } } catch (IOException e) { e.printStackTrace(); } httpResponse.setResponseCode(response.getStatusLine().getStatusCode()); httpResponse.setResponse(result.toString()); try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } return httpResponse; }
From source file:org.rhq.modules.plugins.wildfly10.ASUploadConnection.java
/** * Triggers the real upload to the AS7 instance. At this point the caller should have written * the content in the {@link OutputStream} given by {@link #getOutputStream()}. * /* w w w . j av a2s . c o m*/ * @return a {@link JsonNode} instance read from the upload response body or null if something went wrong. */ public JsonNode finishUpload() { if (filename == null) { // At this point the fileName should have been set whether at instanciation or in #getOutputStream(String) throw new IllegalStateException("Upload fileName is null"); } closeQuietly(cacheOutputStream); SchemeRegistry schemeRegistry = new SchemeRegistryBuilder(asConnectionParams).buildSchemeRegistry(); ClientConnectionManager httpConnectionManager = new BasicClientConnectionManager(schemeRegistry); DefaultHttpClient httpClient = new DefaultHttpClient(httpConnectionManager); HttpParams httpParams = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(httpParams, SOCKET_CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(httpParams, timeout); if (credentials != null && !asConnectionParams.isClientcertAuthentication()) { httpClient.getCredentialsProvider().setCredentials( new AuthScope(asConnectionParams.getHost(), asConnectionParams.getPort()), credentials); // If credentials were provided, we will first send a GET request to trigger the authentication challenge // This allows to send the potentially big file only once to the server // The typical resulting http exchange would be: // // GET without auth <- 401 (start auth challenge : the server will name the realm and the scheme) // GET with auth <- 200 // POST big file // // Note this only works because we use SimpleHttpConnectionManager which maintains only one HttpConnection // // A better way to avoid uploading a big file twice would be to use the header "Expect: Continue" // Unfortunately AS7 replies "100 Continue" even if authentication headers are not present yet // // There is no need to trigger digest authentication when client certification authentication is used HttpGet triggerAuthRequest = new HttpGet(triggerAuthUri); try { // Send GET request in order to trigger authentication // We don't check response code because we're not already uploading the file httpClient.execute(triggerAuthRequest); } catch (Exception ignore) { // We don't stop trying upload if triggerAuthRequest raises exception // See comment above } finally { triggerAuthRequest.abort(); } } String uploadURL = (asConnectionParams.isSecure() ? ASConnection.HTTPS_SCHEME : ASConnection.HTTP_SCHEME) + "://" + asConnectionParams.getHost() + ":" + asConnectionParams.getPort() + UPLOAD_URI; HttpPost uploadRequest = new HttpPost(uploadUri); try { // Now upload file with multipart POST request MultipartEntity multipartEntity = new MultipartEntity(); multipartEntity.addPart(filename, new FileBody(cacheFile)); uploadRequest.setEntity(multipartEntity); HttpResponse uploadResponse = httpClient.execute(uploadRequest); if (uploadResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { logUploadDoesNotEndWithHttpOkStatus(uploadResponse); return null; } ObjectMapper objectMapper = new ObjectMapper(); InputStream responseBodyAsStream = uploadResponse.getEntity().getContent(); if (responseBodyAsStream == null) { LOG.warn("POST request has no response body"); return objectMapper.readTree(EMPTY_JSON_TREE); } return objectMapper.readTree(responseBodyAsStream); } catch (Exception e) { LOG.error(e); return null; } finally { // Release httpclient resources uploadRequest.abort(); httpConnectionManager.shutdown(); // Delete cache file deleteCacheFile(); } }
From source file:org.obiba.opal.rest.client.magma.OpalJavaClient.java
public HttpResponse post(URI uri, File file) throws IOException { HttpPost post = new HttpPost(uri); MultipartEntity me = new MultipartEntity(); me.addPart("fileToUpload", new FileBody(file)); post.setEntity(me);/*from ww w .jav a 2 s.c o m*/ return execute(post); }
From source file:org.fedoraproject.eclipse.packager.api.UploadSourceCommand.java
/** * Upload a missing file to the lookaside cache. * /*from ww w . ja va2 s. com*/ * Pre: upload file is missing as determined by * {@link UploadSourceCommand#checkSourceAvailable()}. * * @param subMonitor * @return The result of the upload. */ private UploadSourceResult upload(final IProgressMonitor subMonitor) throws UploadFailedException { HttpClient client = getClient(); try { String uploadUrl = projectRoot.getLookAsideCache().getUploadUrl().toString(); if (fedoraSslEnabled) { // user requested a Fedora SSL enabled client client = fedoraSslEnable(client); } else if (trustAllSSLEnabled) { // use an trust-all SSL enabled client client = trustAllSslEnable(client); } HttpPost post = new HttpPost(uploadUrl); FileBody uploadFileBody = new FileBody(fileToUpload); // For the actual upload we must not provide the // "filename" parameter (FILENAME_PARAM_NAME). Otherwise, // the file won't be stored in the lookaside cache. MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart(FILE_PARAM_NAME, uploadFileBody); reqEntity.addPart(PACKAGENAME_PARAM_NAME, new StringBody(projectRoot.getSpecfileModel().getName())); reqEntity.addPart(CHECKSUM_PARAM_NAME, new StringBody(SourcesFile.calculateChecksum(fileToUpload))); // Not sure why it's ~ content-length * 2, but that's what it is... final long totalsize = reqEntity.getContentLength() * 2; subMonitor.beginTask(NLS.bind(FedoraPackagerText.UploadSourceCommand_uploadingFileSubTaskName, fileToUpload.getName()), 100 /* use percentage */); subMonitor.worked(0); // Custom listener for progress reporting of the file upload IRequestProgressListener progL = new IRequestProgressListener() { private int count = 0; private int worked = 0; private int updatedWorked = 0; @Override public void transferred(final long bytesWritten) { count++; worked = updatedWorked; if (subMonitor.isCanceled()) { throw new OperationCanceledException(); } // Since this listener may be called *a lot*, don't // do the calculation to often. if ((count % 1024) == 0) { updatedWorked = // multiply by 85 (instead of 100) since upload // progress cannot be 100% accurate. (int) ((double) bytesWritten / totalsize * 85); if (updatedWorked > worked) { worked = updatedWorked; subMonitor.worked(updatedWorked); } } } }; // We need to wrap the entity which we want to upload in our // custom entity, which allows for progress listening. CoutingRequestEntity countingEntity = new CoutingRequestEntity(reqEntity, progL); post.setEntity(countingEntity); // TODO: This may throw some certificate exception. We should // handle this case and throw a specific exception in order to // report this to the user. I.e. advise to use use $ fedora-cert -n HttpResponse response = client.execute(post); subMonitor.done(); return new UploadSourceResult(response); } catch (IOException e) { throw new UploadFailedException(e.getMessage(), e); } catch (GeneralSecurityException e) { throw new UploadFailedException(e.getMessage(), e); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources client.getConnectionManager().shutdown(); } }
From source file:org.openremote.modeler.beehive.Beehive30API.java
/** * Uploads resources from the given input stream to Beehive server. The Beehive REST API * used assumes a zip compressed stream including all relevant resources. The input stream * parameter must match these expectations. <p> * * The access to Beehive is authenticated using the given user's credentials. * * @param archive zip compressed byte stream containing all the resources to upload * to Beehive/*from ww w . j av a 2 s .c om*/ * @param currentUserAccount The user to authenticate in Beehive, along with account information * * * @throws ConfigurationException * If the Beehive REST URL has been incorrectly configured. Will require * reconfiguration and re-deployment of the application. * * @throws NetworkException * If there's an I/O error on the upload stream or the Beehive server * returns an error status * */ @Override public void uploadResources(InputStream archive, UserAccount currentUserAccount) throws ConfigurationException, NetworkException { final String ARCHIVE_NAME = "openremote.zip"; // TODO : must be HTTPS Account acct = currentUserAccount.getAccount(); HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(); addHTTPAuthenticationHeader(httpPost, currentUserAccount.getUsernamePassword().getUsername(), currentUserAccount.getUsernamePassword().getPassword()); String beehiveRootRestURL = config.getBeehiveRESTRootUrl(); String url = beehiveRootRestURL + "account/" + acct.getOid() + "/" + ARCHIVE_NAME; try { httpPost.setURI(new URI(url)); } catch (URISyntaxException e) { throw new ConfigurationException("Incorrectly configured Beehive REST URL ''{0}'' : {1}", e, beehiveRootRestURL, e.getMessage()); } InputStreamBody resource = new InputStreamBody(archive, ARCHIVE_NAME); MultipartEntity entity = new MultipartEntity(); entity.addPart("resource", resource); httpPost.setEntity(entity); HttpResponse response; try { response = httpClient.execute(httpPost); } catch (IOException e) { throw new NetworkException("Network I/O error while uploading resource artifacts to Beehive : {0}", e, e.getMessage()); } if (response.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) { throw new NetworkException("Failed to save resources to Beehive, status code: {0}", response.getStatusLine().getStatusCode()); } // TODO : // - should probably check other return codes explicitly here too, such as // authentication errors (which is most likely not recoverable whereas // a regular network connection glitch might well be)... }
From source file:sjizl.com.FileUploadTest2.java
private void doFileUpload() { String username = ""; String password = ""; String foto = ""; String foto_num = ""; SharedPreferences sp = getApplicationContext().getSharedPreferences("loginSaved", Context.MODE_PRIVATE); username = sp.getString("username", null); password = sp.getString("password", null); foto = sp.getString("foto", null); foto_num = sp.getString("foto_num", null); File file1 = new File(selectedPath1); String urlString = "http://sjizl.com/postBD/UploadToServer.php?username=" + username + "&password=" + password;//from w ww . jav a2 s . c o m try { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(urlString); FileBody bin1 = new FileBody(file1); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("uploadedfile1", bin1); reqEntity.addPart("user", new StringBody("User")); post.setEntity(reqEntity); HttpResponse response = client.execute(post); resEntity = response.getEntity(); final String response_str = EntityUtils.toString(resEntity); if (resEntity != null) { Log.i("RESPONSE", response_str); runOnUiThread(new Runnable() { public void run() { try { res.setTextColor(Color.GREEN); res.setText("n Response from server : n " + response_str); CommonUtilities.custom_toast(getApplicationContext(), FileUploadTest2.this, "Upload Complete! ", null, R.drawable.iconbd); Brows(); } catch (Exception e) { e.printStackTrace(); } } }); } } catch (Exception ex) { Log.e("Debug", "error: " + ex.getMessage(), ex); } //RegisterActivity.login(username,password,getApplicationContext()); }
From source file:bluej.collect.DataCollectorImpl.java
public static void edit(final Package pkg, final File path, final String source, final boolean includeOneLineEdits) { final Project proj = pkg.getProject(); final ProjectDetails projDetails = new ProjectDetails(proj); final FileKey key = new FileKey(projDetails, CollectUtility.toPath(projDetails, path)); final String anonSource = CodeAnonymiser.anonymise(source); final List<String> anonDoc = Arrays.asList(Utility.splitLines(anonSource)); submitEvent(proj, pkg, EventName.EDIT, new Event() { private boolean dontReplace = false; //Edit solely within one line private boolean isOneLineDiff(Patch patch) { if (patch.getDeltas().size() > 1) return false; Delta theDelta = patch.getDeltas().get(0); return theDelta.getOriginal().size() == 1 && theDelta.getRevised().size() == 1; }// w w w .ja va 2 s .c o m @Override public MultipartEntity makeData(int sequenceNum, Map<FileKey, List<String>> fileVersions) { List<String> previousDoc = fileVersions.get(key); if (previousDoc == null) previousDoc = new ArrayList<String>(); // Diff against empty file MultipartEntity mpe = new MultipartEntity(); Patch patch = DiffUtils.diff(previousDoc, anonDoc); if (patch.getDeltas().isEmpty() || (isOneLineDiff(patch) && !includeOneLineEdits)) { dontReplace = true; return null; } String diff = makeDiff(patch); mpe.addPart("source_histories[][content]", CollectUtility.toBody(diff)); mpe.addPart("source_histories[][source_history_type]", CollectUtility.toBody("diff")); mpe.addPart("source_histories[][name]", CollectUtility.toBody(CollectUtility.toPath(projDetails, path))); return mpe; } @Override public void success(Map<FileKey, List<String>> fileVersions) { if (!dontReplace) { fileVersions.put(key, anonDoc); } } }); }