List of usage examples for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE
HttpMultipartMode BROWSER_COMPATIBLE
To view the source code for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE.
Click Source Link
From source file:it.staiger.jmeter.protocol.http.sampler.HTTPHC4DynamicFilePost.java
/** * //from ww w . ja va 2 s . c o m * @param post {@link HttpPost} * @return String posted body if computable * @throws IOException if sending the data fails due to I/O */ @Override protected String sendPostData(HttpPost post) throws IOException { // Buffer to hold the post body, except file content StringBuilder postedBody = new StringBuilder(1000); FileContentServer contentServer = FileContentServer.getServer(); HTTPFileArg staticFiles[] = getHTTPFiles(); HTTPFileArg dynFiles[] = testElement.getDynamicFiles(); VariableFileArg variableFiles[] = testElement.getVariableFiles(); String[] attachmentsNumber = null; boolean thresholdCheck = testElement.getRecordType() >= testElement.getThreshold(); final String contentEncoding = getContentEncodingOrNull(); final boolean haveContentEncoding = contentEncoding != null; boolean hasContent = false; // If a content encoding is specified, we use that as the // encoding of any parameter values Charset charset = null; if (haveContentEncoding) { charset = Charset.forName(contentEncoding); } // Write the request to our own stream MultipartEntity multiPart = new MultipartEntity( getDoBrowserCompatibleMultipart() ? HttpMultipartMode.BROWSER_COMPATIBLE : HttpMultipartMode.STRICT, null, charset); // Create the parts // Add any parameters PropertyIterator args = getArguments().iterator(); while (args.hasNext()) { HTTPArgument arg = (HTTPArgument) args.next().getObjectValue(); String parameterName = arg.getName(); if (arg.isSkippable(parameterName)) { continue; } FormBodyPart formPart; StringBody stringBody = new StringBody(arg.getValue(), charset); formPart = new FormBodyPart(arg.getName(), stringBody); multiPart.addPart(formPart); hasContent = true; } /* * set parameters controlled by threshold */ if (!testElement.getArgumentThreshold() || thresholdCheck) { args = testElement.getOwnArguments().iterator(); while (args.hasNext()) { HTTPArgument arg = (HTTPArgument) args.next().getObjectValue(); String parameterName = arg.getName(); if (arg.isSkippable(parameterName)) { continue; } FormBodyPart formPart; StringBody stringBody = new StringBody(arg.getValue(), charset); formPart = new FormBodyPart(arg.getName(), stringBody); multiPart.addPart(formPart); hasContent = true; } } // Add all files // Cannot retrieve parts once added to the MultiPartEntity, so have to save them here. ViewableByteBody[] viewableByteBodies = new ViewableByteBody[variableFiles.length + staticFiles.length + dynFiles.length]; int i = 0; //Variable Files if (!testElement.getVariableThreshold() || thresholdCheck) for (int j = 0; j < variableFiles.length; j++, i++) { VariableFileArg file = variableFiles[j]; viewableByteBodies[i] = new ViewableByteBody(file.getContent().getBytes(), file.getMimeType(), file.getName()); multiPart.addPart(file.getParamName(), viewableByteBodies[i]); hasContent = true; } //Static Files if (!testElement.getStaticThreshold() || thresholdCheck) for (i = 0; i < staticFiles.length; i++) { HTTPFileArg file = staticFiles[i]; viewableByteBodies[i] = new ViewableByteBody(contentServer.getFileContent(file.getPath()), file.getMimeType(), new File(file.getPath()).getName()); multiPart.addPart(file.getParamName(), viewableByteBodies[i]); hasContent = true; } //Dynamic Files if (!testElement.getDynamicThreshold() || thresholdCheck) { attachmentsNumber = testElement.getAttachmentNumbers().split(","); for (int j = 0; j < attachmentsNumber.length && !attachmentsNumber[j].isEmpty(); i++, j++) { int fileNum = Integer.parseInt(attachmentsNumber[j]) - 1; if (fileNum >= dynFiles.length) { log.warn("trying to send file out of dynamic files range (" + Integer.toString(fileNum + 1) + " of " + Integer.toString(dynFiles.length) + ")\nfile was skipped"); i--; continue; } HTTPFileArg file = dynFiles[fileNum]; viewableByteBodies[i] = new ViewableByteBody(contentServer.getFileContent(file.getPath()), file.getMimeType(), new File(file.getPath()).getName()); multiPart.addPart(file.getParamName(), viewableByteBodies[i]); hasContent = true; } } post.setEntity(multiPart); if (!hasContent) log.warn("POST has no content!"); if (multiPart.isRepeatable()) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); //stop the content from appearing in sampler result if (!testElement.getLogFiles()) { for (ViewableByteBody fileBody : viewableByteBodies) { if (fileBody != null) fileBody.hideFileData = true; else break; } } multiPart.writeTo(bos); //Set it back, in order for the content to be sent if (!testElement.getLogFiles()) { for (ViewableByteBody fileBody : viewableByteBodies) { if (fileBody != null) fileBody.hideFileData = false; else break; } } bos.flush(); // We get the posted bytes using the encoding used to create it postedBody.append(new String(bos.toByteArray(), contentEncoding == null ? "US-ASCII" // $NON-NLS-1$ this is the default used by HttpClient : contentEncoding)); bos.close(); } else { postedBody.append("<Multipart was not repeatable, cannot view what was sent>"); // $NON-NLS-1$ } return postedBody.toString(); }
From source file:org.xmetdb.rest.protocol.CallableProtocolUpload.java
protected HttpEntity createPOSTEntity(DBAttachment attachment) throws Exception { Charset utf8 = Charset.forName("UTF-8"); if ("text/uri-list".equals(attachment.getFormat())) { List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("title", attachment.getProtocol().getIdentifier())); formparams.add(new BasicNameValuePair("dataset_uri", attachment.getDescription())); formparams.add(new BasicNameValuePair("folder", attachment_type.substrate.equals(attachment.getType()) ? "substrate" : "product")); return new UrlEncodedFormEntity(formparams, "UTF-8"); } else {/*from ww w . j a va 2 s. co m*/ if (attachment.getResourceURL() == null) throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Attachment resource URL is null! "); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, utf8); entity.addPart("title", new StringBody(attachment.getTitle(), utf8)); entity.addPart("seeAlso", new StringBody(attachment.getDescription(), utf8)); entity.addPart("license", new StringBody("XMETDB", utf8)); URI uri = attachment.getResourceURL().toURI(); entity.addPart("file", new FileBody(new File(uri))); return entity; } //match, seeAlso, license }
From source file:com.siahmsoft.soundroid.sdk7.provider.tracks.TracksStore.java
public void shareTrack(String idTrack, ArrayList<String> mails, ResultListener<Track> listener) { final Uri uri = buildShareTrackQuery(idTrack); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName(HTTP.UTF_8)); for (String mail : mails) { if (mail != null && !"".equals(mail)) { ContentBody sharedTo;/*w ww .j a v a 2s . c om*/ try { sharedTo = new StringBody(mail.trim()); entity.addPart("track[shared_to][emails][][address]", sharedTo); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } final HttpPut put = new HttpPut(uri.toString()); signRequest(put); put.setEntity(entity); try { executeRequestNotSigned(put, new ResponseHandler() { public void handleResponse(InputStream in) throws IOException { parseSingleResponse(in, new ResponseParserSingle() { @Override public void parseResponse(JSONObject parser) throws JSONException { int i = 0; i++; } }); } }); } catch (IOException e) { android.util.Log.e(LOG_TAG, "Could not perform search with query: ", e); listener.onError(e); } }
From source file:com.siahmsoft.soundroid.sdk7.provider.tracks.TracksStore.java
public void uploadTrack(Bundle bundle, ResultListener<Track> listener) { Track track = TracksStore.Track.fromBundle(bundle); SystemClock.sleep(1500);// w w w. jav a 2 s. co m if (track.getmIdTrack() == 0) { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName(HTTP.UTF_8)); try { if (track.getmTrackPath() != null && !"".equals(track.getmTrackPath())) { ContentBody asset_Data = new FileBody(new File(track.getmTrackPath())); entity.addPart("track[asset_data]", asset_Data); } if (track.getmArtworkPath() != null && !"".equals(track.getmArtworkPath())) { ContentBody artworkData = new FileBody(new File(track.getmArtworkPath())); entity.addPart("track[artwork_data]", artworkData); } if (track.getmTitle() != null && !"".equals(track.getmTitle())) { entity.addPart("track[title]", new StringBody(track.getmTitle())); } if (track.getmDescription() != null && !"".equals(track.getmDescription())) { entity.addPart("track[description]", new StringBody(track.getmDescription())); } if (track.getmDownloadable() != null && !"".equals(track.getmDownloadable())) { entity.addPart("track[downloadable]", new StringBody(track.getmDownloadable())); } if (track.getmSharing() != null && !"".equals(track.getmSharing())) { entity.addPart("track[sharing]", new StringBody(track.getmSharing())); } if (!"".equals(track.getmBpm())) { entity.addPart("track[bpm]", new StringBody(String.valueOf(track.getmBpm()))); } if (track.getmTagList() != null && !"".equals(track.getmTagList())) { entity.addPart("track[tag_list]", new StringBody(track.getmTagList())); } if (track.getmGenre() != null && !"".equals(track.getmGenre())) { entity.addPart("track[genre]", new StringBody(track.getmGenre())); } if (track.getmLicense() != null && !"".equals(track.getmLicense())) { entity.addPart("track[license]", new StringBody(track.getmLicense())); } if (track.getmLabelName() != null && !"".equals(track.getmLabelName())) { entity.addPart("track[label_name]", new StringBody(track.getmLabelName())); } if (track.getmTrackType() != null && !"".equals(track.getmTrackType())) { entity.addPart("track[track_type]", new StringBody(track.getmTrackType())); } HttpPost filePost = new HttpPost("http://api.soundcloud.com/tracks"); signRequest(filePost); filePost.setEntity(entity); executeRequestNotSigned(filePost, new ResponseHandler() { public void handleResponse(InputStream in) throws IOException { parseSingleResponse(in, new ResponseParserSingle() { @Override public void parseResponse(JSONObject parser) throws JSONException { int i = 0; i++; } }); } }); } catch (Exception e) { } /* mBoundUploadService = Soundroid.getUploadService(); mBoundUploadService.uploadTrack(track);*/ } else {//Edicin de la cancin MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName(HTTP.UTF_8)); try { if (track.getmTrackPath() != null && !"".equals(track.getmTrackPath())) { ContentBody asset_Data = new FileBody(new File(track.getmTrackPath())); entity.addPart("track[asset_data]", asset_Data); } if (track.getmArtworkPath() != null && !"".equals(track.getmArtworkPath())) { ContentBody artworkData = new FileBody(new File(track.getmArtworkPath())); entity.addPart("track[artwork_data]", artworkData); } if (track.getmTitle() != null) { entity.addPart("track[title]", new StringBody(track.getmTitle())); } if (track.getmDescription() != null) { entity.addPart("track[description]", new StringBody(track.getmDescription())); } if (track.getmDownloadable() != null) { entity.addPart("track[downloadable]", new StringBody(track.getmDownloadable())); } if (track.getmSharing() != null) { entity.addPart("track[sharing]", new StringBody(track.getmSharing())); } entity.addPart("track[bpm]", new StringBody(String.valueOf(track.getmBpm()))); if (track.getmTagList() != null) { entity.addPart("track[tag_list]", new StringBody(track.getmTagList())); } if (track.getmGenre() != null) { entity.addPart("track[genre]", new StringBody(track.getmGenre())); } if (track.getmLicense() != null) { entity.addPart("track[license]", new StringBody(track.getmLicense())); } if (track.getmLabelName() != null) { entity.addPart("track[label_name]", new StringBody(track.getmLabelName())); } if (track.getmTrackType() != null) { entity.addPart("track[track_type]", new StringBody(track.getmTrackType())); } HttpPut filePut = new HttpPut("http://api.soundcloud.com/tracks/" + track.getmIdTrack() + ".json"); signRequest(filePut); filePut.setEntity(entity); executeRequestNotSigned(filePut, new ResponseHandler() { public void handleResponse(InputStream in) throws IOException { parseSingleResponse(in, new ResponseParserSingle() { @Override public void parseResponse(JSONObject parser) throws JSONException { int i = 0; i++; } }); } }); } catch (Exception e) { } } }
From source file:illab.nabal.proxy.AbstractContext.java
/** * Add multipart data to given HTTP POST object. * //w w w .j a v a 2 s.c o m * @param httpPost * @param params * @param paramNameForFile * @param file * @return HttpPost * @throws Exception */ protected synchronized HttpPost getMultipartHttpPost(HttpPost httpPost, List<NameValuePair> params, String paramNameForFile, File file) throws Exception { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); if (params != null && params.size() > 0) { for (NameValuePair nvPair : params) { entity.addPart(nvPair.getName(), new StringBody(StringHelper.nvl(nvPair.getValue()))); } } // check if given File is an actual file if (file == null || file.isFile() == false) { throw new Exception("File is invalid. check file path."); } else { entity.addPart(paramNameForFile, new FileBody(file)); } httpPost.setEntity(entity); return httpPost; }
From source file:org.botlibre.sdk.SDKConnection.java
public String POSTFILE(String url, String path, String name, String xml) { if (this.debug) { System.out.println("POST: " + url); System.out.println("file: " + path); System.out.println("XML: " + xml); }/*from www . ja v a 2 s. com*/ String result = ""; try { File file = new File(path); FileInputStream stream = new FileInputStream(file); ByteArrayOutputStream output = new ByteArrayOutputStream(); int read = 0; byte[] buffer = new byte[4096]; while ((read = stream.read(buffer)) != -1) { output.write(buffer, 0, read); } byte[] byte_arr = output.toByteArray(); stream.close(); ByteArrayBody fileBody = new ByteArrayBody(byte_arr, name); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); multipartEntity.addPart("file", fileBody); multipartEntity.addPart("xml", new StringBody(xml)); HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = null; HttpPost httppost = new HttpPost(url); httppost.setEntity(multipartEntity); response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); if (entity != null) { result = EntityUtils.toString(entity, HTTP.UTF_8); } if ((response.getStatusLine().getStatusCode() != 200) && (response.getStatusLine().getStatusCode() != 204)) { this.exception = new SDKException("" + response.getStatusLine().getStatusCode() + " : " + result); throw this.exception; } } catch (Exception exception) { this.exception = new SDKException(exception); throw this.exception; } return result; }
From source file:edu.mit.mobile.android.locast.net.NetworkClient.java
/** * Uploads the content using HTTP POST of a multipart MIME document. * * @param context/*from ww w. jav a2 s . com*/ * @param progressListener * @param serverPath * @param localFile * @param contentType * @return * @throws NetworkProtocolException * @throws IOException * @throws JSONException * @throws IllegalStateException */ public JSONObject uploadContentUsingForm(Context context, TransferProgressListener progressListener, String serverPath, Uri localFile, String contentType) throws NetworkProtocolException, IOException, IllegalStateException, JSONException { if (localFile == null) { throw new IOException("Cannot send. Content item does not reference a local file."); } final InputStream is = getFileStream(context, localFile); // next step is to send the file contents. final String postUrl = getFullUrlAsString(serverPath); final HttpPost r = new HttpPost(postUrl); if (DEBUG) { Log.d(TAG, "Multipart-MIME POSTing " + localFile + " (mimetype: " + contentType + ") to " + postUrl); } final InputStreamWatcher isw = new InputStreamWatcher(is, progressListener); final MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); final InputStreamBody fileBody = new AndroidFileInputStreamBody(context, localFile, isw, contentType); if (DEBUG) { Log.d(TAG, "uploadContentUsingForm. content length: " + fileBody.getContentLength()); } reqEntity.addPart("file", fileBody); r.setEntity(reqEntity); final HttpResponse c = this.execute(r); checkStatusCode(c, true); return toJsonObject(c); }