List of usage examples for org.apache.http.entity.mime MultipartEntity addPart
public void addPart(final String name, final ContentBody contentBody)
From source file:bluej.collect.DataCollectorImpl.java
/** * Submits an event and adds a source location. This should be used if the file * is within the project (otherwise see submitEventWithClassLocation) * //from w w w . ja va 2 s. c om * @param project * @param eventName * @param mpe You can pass null if you have no other data to give * @param sourceFile * @param lineNumber */ private static void submitEventWithLocalLocation(Project project, Package pkg, EventName eventName, MultipartEntity mpe, File sourceFile, int lineNumber) { if (mpe == null) { mpe = new MultipartEntity(); } mpe.addPart("event[source_file_name]", CollectUtility.toBodyLocal(new ProjectDetails(project), sourceFile)); mpe.addPart("event[line_number]", CollectUtility.toBody(lineNumber)); submitEvent(project, pkg, eventName, new PlainEvent(mpe)); }
From source file:eg.nileu.cis.nilestore.main.HttpDealer.java
/** * Put.//from w w w . j a va 2 s. co m * * @param filepath * the filepath * @param url * the url * @throws ClientProtocolException * the client protocol exception * @throws IOException * Signals that an I/O exception has occurred. */ public static void put(String filepath, String url) throws ClientProtocolException, IOException { url = url + (url.endsWith("/") ? "" : "/") + "upload?t=json"; HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpPost post = new HttpPost(url); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); File file = new File(filepath); final double filesize = file.length(); ContentBody fbody = new FileBodyProgress(file, new ProgressListener() { @Override public void transfered(long bytes, float rate) { int percent = (int) ((bytes / filesize) * 100); String bar = ProgressUtils.progressBar("Uploading file to the gateway : ", percent, rate); System.err.print("\r" + bar); if (percent == 100) { System.err.println(); System.err.println("wait the gateway is processing and saving your file"); } } }); entity.addPart("File", fbody); post.setEntity(entity); HttpResponse response = client.execute(post); if (response != null) { System.err.println(response.getStatusLine()); HttpEntity ht = response.getEntity(); String json = EntityUtils.toString(ht); JSONParser parser = new JSONParser(); try { JSONObject obj = (JSONObject) parser.parse(json); System.out.println(obj.get("cap")); } catch (ParseException e) { System.err.println("Error during parsing the response: " + e.getMessage()); System.exit(-1); } } else { System.err.println("Error: response = null"); } client.getConnectionManager().shutdown(); }
From source file:bluej.collect.DataCollectorImpl.java
private static synchronized void submitEvent(final Project project, final Package pkg, final EventName eventName, final Event evt) { final String projectName = project == null ? null : project.getProjectName(); final String projectPathHash = project == null ? null : CollectUtility.md5Hash(project.getProjectDir().getAbsolutePath()); final String packageName = pkg == null ? null : pkg.getQualifiedName(); // We take a copy of these internal variables, so that we don't have a race hazard // if the variable changes between now and the event being sent: final String uuidCopy = DataCollector.getUserID(); final String experimentCopy = DataCollector.getExperimentIdentifier(); final String participantCopy = DataCollector.getParticipantIdentifier(); /**/* w ww. j a v a 2 s .c om*/ * Wrap the Event we've been given to add the other normal expected fields: */ DataSubmitter.submitEvent(new Event() { @Override public void success(Map<FileKey, List<String>> fileVersions) { evt.success(fileVersions); } @Override public MultipartEntity makeData(int sequenceNum, Map<FileKey, List<String>> fileVersions) { MultipartEntity mpe = evt.makeData(sequenceNum, fileVersions); if (mpe == null) return null; mpe.addPart("user[uuid]", CollectUtility.toBody(uuidCopy)); mpe.addPart("session[id]", CollectUtility.toBody(DataCollector.getSessionUuid())); mpe.addPart("participant[experiment]", CollectUtility.toBody(experimentCopy)); mpe.addPart("participant[participant]", CollectUtility.toBody(participantCopy)); if (projectName != null) { mpe.addPart("project[name]", CollectUtility.toBody(projectName)); mpe.addPart("project[path_hash]", CollectUtility.toBody(projectPathHash)); if (packageName != null) { mpe.addPart("package[name]", CollectUtility.toBody(packageName)); } } mpe.addPart("event[source_time]", CollectUtility.toBody(DateFormat.getDateTimeInstance().format(new Date()))); mpe.addPart("event[name]", CollectUtility.toBody(eventName.getName())); mpe.addPart("event[sequence_id]", CollectUtility.toBody(Integer.toString(sequenceNum))); return mpe; } }); }
From source file:com.uf.togathor.db.couchdb.ConnectionHandler.java
public static String getIdFromFileUploader(String url, List<NameValuePair> params) throws IOException, UnsupportedOperationException { // Making HTTP request // defaultHttpClient HttpParams httpParams = new BasicHttpParams(); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(httpParams, "UTF-8"); HttpClient httpClient = new DefaultHttpClient(httpParams); HttpPost httpPost = new HttpPost(url); httpPost.setHeader("database", Const.DATABASE); Charset charSet = Charset.forName("UTF-8"); // Setting up the // encoding/* w ww. j ava2 s. c o m*/ MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (int index = 0; index < params.size(); index++) { if (params.get(index).getName().equalsIgnoreCase(Const.FILE)) { // If the key equals to "file", we use FileBody to // transfer the data entity.addPart(params.get(index).getName(), new FileBody(new File(params.get(index).getValue()))); } else { // Normal string data entity.addPart(params.get(index).getName(), new StringBody(params.get(index).getValue(), charSet)); } } httpPost.setEntity(entity); print(httpPost); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); InputStream is = httpEntity.getContent(); // if (httpResponse.getStatusLine().getStatusCode() > 400) // { // if (httpResponse.getStatusLine().getStatusCode() == 500) throw new SpikaException(ConnectionHandler.getError(entity.getContent())); // throw new IOException(httpResponse.getStatusLine().getReasonPhrase()); // } // BufferedReader reader = new BufferedReader(new // InputStreamReader(is, "iso-8859-1"), 8); BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } is.close(); String json = sb.toString(); Logger.debug("RESPONSE", json); return json; }
From source file:bluej.collect.DataCollectorImpl.java
public static void addClass(Package pkg, File sourceFile) { final MultipartEntity mpe = new MultipartEntity(); final ProjectDetails projDetails = new ProjectDetails(pkg.getProject()); final String contents = CollectUtility.readFileAndAnonymise(projDetails, sourceFile); mpe.addPart("project[source_files][][name]", CollectUtility.toBodyLocal(projDetails, sourceFile)); mpe.addPart("source_histories[][source_history_type]", CollectUtility.toBody("complete")); mpe.addPart("source_histories[][name]", CollectUtility.toBodyLocal(projDetails, sourceFile)); mpe.addPart("source_histories[][content]", CollectUtility.toBody(contents)); final FileKey key = new FileKey(projDetails, CollectUtility.toPath(projDetails, sourceFile)); submitEvent(pkg.getProject(), pkg, EventName.ADD, new Event() { @Override/*www.j av a 2 s . co m*/ public void success(Map<FileKey, List<String>> fileVersions) { fileVersions.put(key, Arrays.asList(Utility.splitLines(contents))); } @Override public MultipartEntity makeData(int sequenceNum, Map<FileKey, List<String>> fileVersions) { return mpe; } }); }
From source file:net.java.sip.communicator.service.httputil.HttpUtils.java
/** * Posts a <tt>file</tt> to the <tt>address</tt>. * @param address the address to post the form to. * @param fileParamName the name of the param for the file. * @param file the file we will send.//ww w . j av a 2s .c om * @param usernamePropertyName the property to use to retrieve/store * username value if protected site is hit, for username * ConfigurationService service is used. * @param passwordPropertyName the property to use to retrieve/store * password value if protected site is hit, for password * CredentialsStorageService service is used. * @return the result or null if send was not possible or * credentials ask if any was canceled. */ public static HTTPResponseResult postFile(String address, String fileParamName, File file, String usernamePropertyName, String passwordPropertyName) { DefaultHttpClient httpClient = null; try { HttpPost postMethod = new HttpPost(address); httpClient = getHttpClient(usernamePropertyName, passwordPropertyName, postMethod.getURI().getHost(), null); String mimeType = URLConnection.guessContentTypeFromName(file.getPath()); if (mimeType == null) mimeType = "application/octet-stream"; FileBody bin = new FileBody(file, mimeType); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart(fileParamName, bin); postMethod.setEntity(reqEntity); HttpEntity resEntity = executeMethod(httpClient, postMethod, null, null); if (resEntity == null) return null; return new HTTPResponseResult(resEntity, httpClient); } catch (Throwable e) { logger.error("Cannot post file to:" + address, e); } return null; }
From source file:mobi.salesforce.client.upload.DemoFileUploader.java
public void executeMultiPartRequest(String urlString, File file, String fileName, String fileDescription) throws Exception { HttpClient client = new DefaultHttpClient(); HttpPost postRequest = new HttpPost(urlString); try {/* ww w .j a va 2s . co m*/ // Set various attributes MultipartEntity multiPartEntity = new MultipartEntity(); multiPartEntity.addPart("fileDescription", new StringBody(fileDescription != null ? fileDescription : "")); multiPartEntity.addPart("fileName", new StringBody(fileName != null ? fileName : file.getName())); FileBody fileBody = new FileBody(file, "application/octect-stream"); // Prepare payload multiPartEntity.addPart("attachment", fileBody); // Set to request body postRequest.setEntity(multiPartEntity); // Send request HttpResponse response = client.execute(postRequest); // Verify response if any if (response != null) { System.out.println(response.getStatusLine().getStatusCode()); } } catch (Exception ex) { } }
From source file:ADP_Streamline.CURL.java
public void UploadFiles() throws ClientProtocolException, IOException { String filePath = "file_path"; String url = "http://localhost/files"; File file = new File(filePath); MultipartEntity entity = new MultipartEntity(); entity.addPart("file", new FileBody(file)); HttpResponse returnResponse = Request.Post(url).body(entity).execute().returnResponse(); System.out.println("Response status: " + returnResponse.getStatusLine().getStatusCode()); System.out.println(EntityUtils.toString(returnResponse.getEntity())); }
From source file:bluej.collect.DataCollectorImpl.java
public static void packageOpened(Package pkg) { final ProjectDetails proj = new ProjectDetails(pkg.getProject()); final MultipartEntity mpe = new MultipartEntity(); final Map<FileKey, List<String>> versions = new HashMap<FileKey, List<String>>(); for (ClassTarget ct : pkg.getClassTargets()) { String relative = CollectUtility.toPath(proj, ct.getSourceFile()); mpe.addPart("project[source_files][][name]", CollectUtility.toBody(relative)); String anonymisedContent = CollectUtility.readFileAndAnonymise(proj, ct.getSourceFile()); if (anonymisedContent != null) { mpe.addPart("source_histories[][source_history_type]", CollectUtility.toBody("complete")); mpe.addPart("source_histories[][name]", CollectUtility.toBody(relative)); mpe.addPart("source_histories[][content]", CollectUtility.toBody(anonymisedContent)); versions.put(new FileKey(proj, relative), Arrays.asList(Utility.splitLines(anonymisedContent))); }//from ww w . j ava 2 s.co m } submitEvent(pkg.getProject(), pkg, EventName.PACKAGE_OPENING, new Event() { @Override public void success(Map<FileKey, List<String>> fileVersions) { fileVersions.putAll(versions); } @Override public MultipartEntity makeData(int sequenceNum, Map<FileKey, List<String>> fileVersions) { return mpe; } }); }
From source file:org.apache.sling.validation.testservices.ValidationServiceTest.java
@Test public void testValidRequestModel1() throws IOException, JSONException { MultipartEntity entity = new MultipartEntity(); entity.addPart("sling:resourceType", new StringBody("validation/test/resourceType1")); entity.addPart("field1", new StringBody("HELLOWORLD")); entity.addPart("field2", new StringBody("30.01.1988")); entity.addPart(SlingPostConstants.RP_OPERATION, new StringBody("validation")); RequestExecutor re = getRequestExecutor().execute( getRequestBuilder().buildPostRequest("/validation/testing/fakeFolder1/resource").withEntity(entity)) .assertStatus(200);//from www.j a v a 2 s .c o m JSONObject jsonResponse = new JSONObject(re.getContent()); assertTrue(jsonResponse.getBoolean("valid")); }